开发者

is there a way to select :first-word of <p>?

like we select p:first-letter? I know there is no property called p:first-word but if any other way SO user 开发者_开发问答knows.

I don't want to add anything in HTML.


$('p').each(function(){
    var me = $(this)
       , t = me.text().split(' ');
    me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
  });

This bolds first word.

or

$('p').each(function(){
    var me = $(this);
    me.html( me.text().replace(/(^\w+)/,'<strong>$1</strong>') );
  });


This isn't difficult in JavaScript - there's example code here (you'll need to view source to see how it works, but it does work). It doesn't depend on jQuery or any other libraries, as far as I can see.


You can do it in JavaScript by finding the DOM node you are interested on and taking the .innerHTML of it, adding around the first word and storing back to .innerHTML.


You can extract the full text from the p and grab the first word with a regexp:

$('p').click(function() {
    var word = /^\w+/.exec($(this).text());
    alert(word);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜