Monday, May 27, 2019

CSS selector - element with a given child




I'm looking to make a selector which will select all elements if they have a specific child element. For example, select all

with a child .



Possible?


Answer




Is it possible to select an element if it contains a specific child element?




Unfortunately not yet.



The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.






A Note About Specification Changes



This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.






An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.



The subject was going to be the element in the selector chain that would have styles applied to it.



Example HTML

lorem ipsum dolor sit amet


consecteture edipsing elit




This selector would style the span element



p span {
color: red;
}


This selector would style the p element



!p span {
color: red;
}





A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()"



:has() would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has() pseudo-selector*.



In any event, continuing the example from above, to select the p element that contains a span one could use:



p:has(span) {
color: red;
}





* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...