DEV Community

Cover image for A css-selector that a parent with child
Timothy Huang
Timothy Huang

Posted on

A css-selector that a parent with child

Sometimes we want to select elements with known child, we can use :has() selector, but no browser support now. (just check can i use :has() - https://caniuse.com/?search=%3Ahas())

However, we can use jQuery to select these elements by :has() like $("div:has(span.red)").

There is an example to show how it works:

https://codepen.io/timhuang/pen/jOqpxbY

$("div:has(span.red)").append("<p>this paragraph was added by jquery</p>"); 
Enter fullscreen mode Exit fullscreen mode

jQuery is support the :has() pseudo-class just a draft on W3C:

https://drafts.csswg.org/selectors-4/#relational

After the draft turning into specification we can use :has(), maybe css 4.

Top comments (2)

Collapse
 
ingosteinke profile image
Ingo Steinke

Parent selectors are finally here! Or rather, there, as Safari is the first browser to implement them: dev.to/ingosteinke/css-hasparent-s...

Collapse
 
timhuang profile image
Timothy Huang

Great! Thanks for your information.