Ahmad
Ahmad

Reputation: 13406

Select element based on how many children it has?

I have a HTML code like this:

<div class="main"></div>
<div class="span2">
    <div><a href="xyz71">List 1</a></div>
    <div>
        <ul>
            <li><a href="xyz71_72">Cat 11</a>
            </li>
            <li><a href="xyz71_73">Cat 12</a>
            </li>
            <li><a href="xyz71_76">Cat 13</a>
            </li>
            <li><a href="xyz71_78">Cat 14</a>
            </li>
        </ul>
    </div>
</div>
<div class="span2">
    <div><a href="xyz90">List 2</a></div>
    <div>
        <ul>
            <li><a href="xyz90_91">Cat 211</a>
            </li>
            <li><a href="xyz90_92">Cat 212</a>
            </li>
            <li><a href="xyz90_93">Cat 213</a>
            </li>
        </ul>
    </div>
    <div>
        <ul>
            <li><a href="xyz90_91">Cat 221</a>
            </li>
            <li><a href="xyz90_92">Cat 222</a>
            </li>
            <li><a href="xyz90_93">Cat 223</a>
            </li>
            <li><a href="xyz90_94">Cat 224</a>
            </li>
            <li><a href="xyz90_95">Cat 225</a>
            </li>
            <li><a href="xyz90_96">Cat 226</a>
            </li>
        </ul>
    </div>
</div>

JSFiddle: http://jsfiddle.net/LUJmd/1/

main div is the parent. It has 2 child div, both of class span2. The first span2 div only has 2 child elements. But the second span2 div has 3 child elements.

I want to detect divs inside main which contain exactly 3 child elements. When such an element is found, a border should be applied to that element. So in my code, the second span2 element should get a border around it.

I have found the following code for this purpose, but I cannot find a way to use it here.

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

Source: Can CSS detect the number of children an element has?

Can someone help me with this ?

Upvotes: 0

Views: 119

Answers (1)

Chad
Chad

Reputation: 5408

It's not perfect, but if you're able to set a position: relative; on your container divs, you can use pseudo elements to do this.

#container > div {
    position: relative;
}
#container > div div:nth-child(3):after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border: 1px solid #000;
    z-index: -1;
}

Fiddle

Upvotes: 1

Related Questions