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>

6 thoughts on “Ignore element in HTML string”

  1. 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) {
      //clone element then remove children from it and get only text
      var text = $(e).clone().children().remove().end().text().trim();
      console.log(text);
      text = text.trim().split(' ');
      if (text.length > 3) {
        var lastWord = text.pop();
        text = text.join(' ') + "&nbsp;" + lastWord;
        $(e).html(text);
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h3>Yes to the h3 but <i class="fa"></i> not the i</h3>
    Reply

Leave a Comment