Aug 18, 2017

jquery / CSS selector - multiple class delimited with space, comma and greater then

When selecting more then one css class in jQuery or CSS stylesheet one must understand the subtle differences. When to use space, comma and greater then.

Let's take a look at this HTML:

<div id="level1" class="parent">
<span id="spanL1">L1</span>
<div id="level2">
<span id="spanL2">L2</span>
<div id="level3" class="child">
<span id="spanL3">L3</span>
Dummy
</div>
</div>
</div>
<div id="level11" class="sibling">
<span id="spanL11" class="child">L11</span>
<div id="level22">
<span id="spanL22">L22</span>
<div id="level33">
<span id="spanL33" class="child">L33</span>
Dummy
</div>
</div>
</div>

Here are jQuery selectors and their effect :

//Hides  L3
$('.parent .child').hide();
//Hides L3 and L33
$('.child').hide();
//Hides L1, L2, L3 & L11 & L33 - makes no sense since class child is contained by class parent
$('.parent, .child').hide();
// Nothing! Since class child is not direct child of class parent
$('.parent > .child').hide();
//Hides L11 since L11 is first child of sibling and L33 is not
$('.sibling > .child').hide();

Bottom line:
- space - Inheritance      ( parent child )
- comma - enumerating   (column1, column2)
- greater then - direct successor  (parent > directChild)

Example for inheritance:
<div class="login2">
<div class="form-group">
        <input type="submit" value="@Lsr("Users.Login.Login")" class="btn btn-primary" />
        <input type="submit" name="ForgotPassword" class="btn btn-link" />

    </div>
</div>

I want to override first CSS selector with second:

.login2 INPUT[type="submit"]:hover {
    background-color: #4B86B7
}

// DOES NOT OVERRIDE!
.login2 .btn .btn-link INPUT[type="submit"]:hover {
    background-color: white
}

//OK !
.login2 .form-group INPUT[type="submit"]:hover {
    background-color: white
}

CSS selector is selected based on more specific selector BUT as you can see winner is parent->child specificity and NOT putting a lot of CSS class on one level together.

No comments:

Post a Comment