eric.dummy
eric.dummy

Reputation: 399

How to use $(this) in this example?

I've made a small trivial script, where I'm checking if the class exists and then applying the logic.

Here it is:

if($('h3').is('.ui-accordion-header-active')){
   $('h3').css('background', 'red');
}
else {
    $('h3').css('background', 'black');
}

as you can see it is very simple. Now, lets say I have multiple h3 elements on the page and I want to make browser know which one has the class applied. I have tried placing $(this) but that didn't do much. Of course, I can assign the ID and target the element by IDs, but I don't want to do that.

How can I make it more dynamic, so that $(this) can be used or something like $('h3' > this)?

Thanks.

Upvotes: 0

Views: 111

Answers (2)

gavgrif
gavgrif

Reputation: 15499

As pointed out - CSS is the required answer here

h3{background:black}
.ui-accordion-header-active{background:red}

This has to be much faster than any jvascript / jquery solution but if you wanted to do it with jQuery - you don't need to iterate over anything - simply use the selector as follows:

 $('.ui-accordion-header-active').css('background', 'red');

You should still set the h3 background as the css base and then the active class will overide it for the active link:

h3{background:black}

h3{background:black;color:white}
.ui-accordion-header-active{background:red}
<h3>H3 test</h3>
<h3 class="ui-accordion-header-active">H3 ui-accordion-header-active test</h3>

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074168

As Rory pointed out, this is what CSS is for.

But you've said you want to do it in JavaScript with jQuery, you'd use an each loop in the general case, or a css loop in this specific case:

The general case:

$('h3').each(function() {
    var $this = $(this);
    if ($this.is('.ui-accordion-header-active')) {
        $this.css('background', 'red');
    }
    else {
        $this.css('background', 'black');
    }
});

...which can also be rather more simply written:

$('h3').each(function() {
    var $this = $(this);
    $this.css('background', $this.is('.ui-accordion-header-active') ? 'red' : 'black');
});

But since we're setting a property with css, we can use the css function's ability to call a callback:

$('h3').css('background', function() {
    return $(this).is('.ui-accordion-header-active') ? 'red' : 'black';
});

Also, $this.is('.some-class') can more efficiently be written $this.hasClass('some-class') (avoids firing up a full selector matching engine).

In fact, on modern browser, we can be even more efficient by avoiding $(this) entirely using classList:

$('h3').css('background', function() {
    return this.classList.contains('ui-accordion-header-active') ? 'red' : 'black';
});

Upvotes: 6

Related Questions