Reputation: 9043
I wanted to make a really simple script to deal with some orphaned words in some of my headlines. I thought I did a pretty neat job, but then the first words get cut off. Any help understanding why?
var buddyUpOrphans = function(element, howMany) {
$(element).each( function() {
var $this = $(this);
var thisText = $this.text().split(' ');
var wordLength = thisText.length;
thisText.splice( (wordLength - howMany), 0, '<nobr>');
thisText.shift('</nobr>');
thisText = thisText.join(' ');
$this.html(thisText);
});
};
$(document).ready( function() {
buddyUpOrphans('p', 2);
buddyUpOrphans('.test1', 4);
});
Upvotes: 3
Views: 50
Reputation: 142987
The .shift
method removes the first element of the array (and doesn't take any arguments), whereas is seems like you want to add something to the end of the array. You can use the .push
method for this.
Since you are adding the <nobr>
and </nobr>
as elements to the array, and then doing .join(" ")
, this does have the unintended consequence of putting spaces around them.
I would recommend concatenating the <nobr>
and </nobr>
at the end of some elements of the array rather than insering them into the array.
var buddyUpOrphans = function(element, howMany) {
$(element).each( function() {
var $this = $(this);
var thisText = $this.text().split(' ');
var wordLength = thisText.length;
thisText[wordLength - howMany - 1] += "<nobr>";
thisText[wordLength - 1] += '</nobr>';
thisText = thisText.join(' ');
$this.html(thisText);
});
};
$(document).ready( function() {
buddyUpOrphans('p', 2);
buddyUpOrphans('.test1', 4);
});
body {
color: red;
}
nobr {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='test1'>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet voluptates aperiam cumque, qui error, aliquam velit hic ad sapiente accusamus totam id similique repudiandae doloribus, optio consequatur, voluptatum maiores quod?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa laudantium rem ut id delectus at eaque inventore rerum, dolorem nisi alias modi asperiores recusandae nulla, iure. Facilis consequatur, impedit ipsa.</p>
Upvotes: 2
Reputation: 5314
Because you are using arr.shift()
;
It removes the first element of the array and returns that array.
To add elements, use arr.push()
;
Upvotes: 1