2

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.

Community
  • 1
  • 1

3 Answers3

2

@Joseph re: fiddle example Wouldn't replace be easier?

$("#target p").each(function(){
  $(this).html($(this).text().replace(/^([^\s]+)\s?/, '<span>$1</span> '));
});
dakdad
  • 2,947
  • 2
  • 22
  • 21
  • Yes... yes that would be much *much* better :P Thank you much, dakdad. – Joseph Marikle Jul 28 '11 at 18:30
  • @Joseph the only downside is that the bound events are lost - unless they are live events of course as explained in [this question](http://stackoverflow.com/questions/5458605/first-word-selector) – dakdad Jul 28 '11 at 23:47
0

Edit

dakdad has a much better solution: fiddle

@Michael Cornett: could you mark dakdad as answer please? :)

Community
  • 1
  • 1
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
0
$(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