Apply different style to first ul with class name

I have the following HTML structure. I want to select the first ul with the class name "second class" and apply a width that is different from the second ul with the same class name.

<div>
    <div class='Link1'>
        <a>Products</a>
        <div class = 'firstClass'>
            <ul class='secondClass'>
                <li></li>
                <li></li>
            </ul>
        </div>
    </div>
    <div class='Link1'>
        <a>Tools</a>
        <div class = 'firstClass'>
            <ul class='secondClass'>
                <li></li>
                <li></li>
            </ul>
        </div>
    </div>
<div>

      

I tried below css but didn't work.

.Link1 > .firstClass > ul.secondClass:first-child{
    width:750px;
}

      

+3


source to share


1 answer


Using only CSS, there is no way to stop a rule from being applied after it has been applied on one element. This basically means

 .Link1 > .firstClass > ul.secondClass:first-child

      

will apply to all elements that match this selector.

However, you can easily apply another class to just the first match using JavaScript:

var firstMatch = document.querySelector('.Link1 > .firstClass > ul.secondClass:first-child');
firstMatch.className = firstMatch.className + ' additionalClass';

      

... and of course you will need to style additionalClass

in your CSS:



.Link1 > .firstClass > ul.secondClass.additionalClass:first-child {
  /* CSS here */
}

      

Using jQuery this would be:

$('.Link1 > .firstClass > ul.secondClass:first-child').first().addClass('additionalClass');

      


Here a working example , unlike the original, doesn't work .

0


source







All Articles