CSS or jQuery receiving _with_ first-child elements of a specific type

Is there a way in CSS (IE7 +) or jQuery to select elements whose first child has a certain type, for example, as the following pseudocode, you can select all li with the first child of a:

li:first-child(a) 

Update

I was looking for the @SLaks proposed solution because I wanted to get it in one selector. However .parent () method is faster, see http://jsfiddle.net/c4urself/Qw8fX/

 $("li > a:first-child").parent() 

vs.

 $("li:has(>a:first-child)") 

Update 2

See performance differences between the two methods here: jsPerf

http://jsperf.com/jquery-has-child-vs-parent-child-and-parent

+4
source share
4 answers

CSS cannot do this, but jQuery can:

 li:has(>a:first-child) 

CSS cannot do this because CSS was designed for direct access because the browser reads HTML. You can always determine which CSS rules apply to an element immediately, without waiting for children or subsequent siblings to appear.

+4
source

in jQuery $('ul li a:first-child').parent();

+3
source

Using the psuedo li: first-child class, you can apply the required style to the li element, which will then style the a that was nested inside it. Take a look at http://reference.sitepoint.com/css/pseudoclass-firstchild

0
source

I don't think this is possible in CSS, but in jQuery you would like to use filter() .

Make sure you filter based on contents() , not children() , since you want to see text nodes.

 $( function() { $('li').filter( function() { return $(this).contents().first().is('a'); }).each( function() { $('body').append($(this).text() + '<br/>'); }); }); 

http://jsbin.com/olufan

It takes a bit more code than all this in the jQuery selector, but performance should be much better. JQuery selectors really work faster when specifying a single term.

0
source

Source: https://habr.com/ru/post/1386324/


All Articles