Question

This script is driving me crazy, its main feature is to avoid orphans on long headings.

Everything worked well until I realized that if I added any sort of markup to the <h1> (an <a href="#"> in this case), the markup gets stripped out, hence, the link is lost.

This is the current script:

$('h1').each(function() {
  var wordArray = $(this).text().split(' ');
  if (wordArray.length > 1) {
    wordArray[wordArray.length-2] += '&nbsp;' + wordArray[wordArray.length-1];
    wordArray.pop();
    $(this).html(wordArray.join(' '));
  }
});

Here's a simple demo.

Any guidance is greatly appreciated.

Thanks,

Was it helpful?

Solution

The problem comes from your usage of the .text() function to get the content of the header. That automatically strips out any markup, returning only the text nodes. What you need to do is get the HTML (use .html() rather than .text()) then check for the presence of closing tags at the end of the last word to append back to the new content for your header element:

$('h1').each(function() {
    var wordArray = $(this).html().split(' ');
    if (wordArray.length > 1) {
        wordArray[wordArray.length-2] += '&nbsp;' + wordArray[wordArray.length-1];

        var lastWord = wordArray.pop();
        lastWord = lastWord.replace(/.*((?:<\/\w+>)*)$/, '$1');
        $(this).html(wordArray.join(' ') + lastWord);
    }
});

jsFiddle demo

OTHER TIPS

$(this).html(wordArray.join(' '));  //Line causing the issue.

Since your replacing the entire html inside h1 the hyperlink is vanished.

So instead of targeting h1, change the script to handle the a tag like below

$('h1 a').each(function() {
  var wordArray = $(this).text().split(' ');
  if (wordArray.length > 1) {
    wordArray[wordArray.length-2] += '&nbsp;' + wordArray[wordArray.length-1];
    wordArray.pop();
    $(this).html(wordArray.join(' '));
  }
});

Check this JSFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top