在jQuery中select一个包装元素

我正在jquery和nodejs在一个漂亮的旧网站做一些过滤,我想select由p包裹的b元素。 我的意思只是那些没有文字的p包装。

我想要匹配的

 <p><b>Some text</b></p> 

我不想匹配的

 <p>Some other text and some other elements <a>link</a><b>Some text</b> and some more text of the parent p </p> 

你知道我可以select这第一个包裹的元素,而不是第二个? 有没有select器来select这个?

您可以使用filter方法:

 $('p > b').filter(function() { return $(this.parentNode) // get the p element .contents() // get all the child nodes .not(this) // exclude the current `b` element .length === 0; }); 

http://jsfiddle.net/3v6w8a8y/

尝试使用:first-childselect器

 alert($(">b:first-child", "p").text()) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <p><b>Some text</b></p> What I don't want to match <p>Some other text and some other elements <a>link</a><b>Some text</b> and some more text of the parent p </p> 

不确定。 你看起来像这样吗?

HTML

  <p>Some other text and some other elements <a>link</a><b>Some text</b> and some more text of the parent p</p> <p><b>Some text</b></p> <p>Some other text and some other elements <a>link</a><b>Some text</b> 

和一些更多的父母文本

CSS

  pb:first-child:nth-of-type(1) { font-size:30px; } 

DEMO

使用substring()检查html()的前3个字母是否等于<b>

 $("p").each(function() { if ($(this).html().substring(0, 3) == "<b>") { // Do whatever } }); 

如这个JSFiddle Demo所示。