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] += ' ' + wordArray[wordArray.length-1];
wordArray.pop();
$(this).html(wordArray.join(' '));
}
});
Here's a simple demo.
Any guidance is greatly appreciated.
Thanks,
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] += ' ' + wordArray[wordArray.length-1];
var lastWord = wordArray.pop();
lastWord = lastWord.replace(/.*((?:<\/\w+>)*)$/, '$1');
$(this).html(wordArray.join(' ') + lastWord);
}
});