Search code examples
jquerycssjquery-selectorscss-selectors

css selector understanding


I am trying to select the first immediate child <p> element of <li> element that contains an immediate <ul> child.

li>ul:parent>p:first-child

is what I have tried, thinking it will get the li's with immediate ul's then go back to the original li's with the :parent selector then select the immediate p's children that are first.

e.g.

<ul>
    <li>
        <p>SELECT ME!</p>
        <ul>
            <li><!--some more stuff-->
        </ul>
    </li>
</ul>

following the comments I should say that I am using this in a jQuery selector and I found the :parent selector in the jQuery API pages.


Solution

  • The problem that you have is that li > ul:parent will select the <ul> element, but specifying > p:first-child does not match anything, since your p element is within the li, not a direct descendent of the <ul>.

    You can use jQuery's :has() selector for this:

    $('li:has(ul) > p:first-child').css('background-color', 'red');
    

    Here's a jsFiddle demo.

    Unfortunately, I don't think this is possible with pure CSS.