Junky
Junky

Reputation: 1026

Ignore element in HTML string

I'm using the following script to prevent orphaned words (one word on a line by itself) by inserting   between the last two words and I'm applying this to specific elements.

I want to prevent this from applying to tag inside a heading tag:

<h3>Yes to the h3 but <i class="fa"></i> not the i</h3>
// Prevent orphaned words for strings with more than 3 words
$("p:not(.form-row),h1,h2,h3,h4,h5,h6").each(function (i, e) {
    var text = $(e).html().find('i').remove();
    console.log(text);
    text = text.trim().split(' ');
    if (text.length > 3) {
        var lastWord = text.pop();
        text = text.join(' ') + "&nbsp;" + lastWord;
        $(e).html(text);
    }
});

Actual result:

<h3>Common FAQs<i class="fa&nbsp;fa-angle-right fa-angle-right fa-angle-down"></i></h3>

Desired result:

<h3>Common FAQs<i class="fa fa-angle-right fa-angle-right fa-angle-down"></i></h3>

Upvotes: 1

Views: 529

Answers (2)

Junky
Junky

Reputation: 1026

I have decided to remove the tag from the element at the source and use it as a pseudo element on the instead. Thanks everyone!

Upvotes: 0

Swati
Swati

Reputation: 28522

If you need to remove i tag from h3 element you can just clone that element using .clone and remove children from that tags and only get texts.

Demo Code :

$("p:not(.form-row),h1,h2,h3,h4,h5,h6").each(function(i, e) {
  var cloned = $(e).find('i') //take i tag ..
  //clone element then remove children from it and get only text
  var text = $(e).clone().children().remove().end().text();
  text = text.trim().split(' ');
  console.log(text)
  if (text.length > 3) {
    var lastWord = text.pop();
    text = text.join(' ') + "&nbsp;" + lastWord;
    $(e).html(text);
    $(e).append(cloned); //append that i tag ...

  }
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Common FAQs<i class="fa fa-angle-right fa-angle-right fa-angle-down"></i></h3>
<h3>Common FAQs abc ffd<i class="fa fa-angle-right fa-angle-right fa-angle-down"></i></h3>
<h3>Common FAQs abc ffd vlkd.v<i class="fa fa-angle-right fa-angle-right fa-angle-down"></i></h3>

Upvotes: 2

Related Questions