Reputation: 23
I have referenced the following Q&A: First word selector
I am looking to use the same sort of <span></span>
setup, however, I would like for it to occur for every first word of every <p>
within a particular <div>
. How can I specify this?
$(window).load(function(){
(function () {
var node = $("p").contents().filter(function () { return this.nodeType == 3 }).first(),
text = node.text(),
first = text.slice(0,text.indexOf(" "));
if (!node.length)
return;
node[0].nodeValue = text.slice(first.length);
node.before('<span>' + first + '</span>');
})();
});
Within the stylesheet, I then can take the simple <span></span>
that's been applied to various selectors, and specify what the 'span' function will do with each selector.
Upvotes: 2
Views: 1435
Reputation: 1
$(window).load(function(){
$("p").each(function(){
var text = $(this).text() + " ";
var newMarkup =
"<span class='firstWord'>" +
text.substr(0,text.indexOf(" ")) +
"</span>" +
text.substr(text.indexOf(" "));
$(this).html(newMarkup);
});
});
Here is a link to a sample of what I'm working with: http://www.meestro.com/vespers
Upvotes: 0
Reputation: 78530
dakdad has a much better solution: fiddle
@Michael Cornett: could you mark dakdad as answer please? :)
Upvotes: 0
Reputation: 2955
@Joseph re: fiddle example Wouldn't replace be easier?
$("#target p").each(function(){
$(this).html($(this).text().replace(/^([^\s]+)\s?/, '<span>$1</span> '));
});
Upvotes: 2