Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery or JavaScript, select child element adjoining the parent

I'm trying to select the child elements which are joined with the parent. For example, in the following HTML, I only want to select the child (strong) of the second and fourth paragraphs, since in those two cases the child & parent are adjoining (i.e. no text or markup between the child & parent elements):

<p>This is line <strong>number one</strong></p>
<p><strong>This is line number two</strong></p>
<p>This <strong>is line number three</strong></p>
<p><strong>This is line</strong> number four</p>

How can I do this with just the selectors if possible?!

like image 232
Nick Avatar asked Apr 11 '26 19:04

Nick


1 Answers

You can use the filter method:

$('p > strong').filter(function(){
   return !this.previousSibling;
});

FIDDLE

like image 191
undefined Avatar answered Apr 13 '26 12:04

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!