SeanBallentine
SeanBallentine

Reputation: 173

Add class to div when clicked

I am trying to get a class to be added to a div element when clicked. I can not get it to work, I have it set up similar to this:

javascript:

function choose() {
    this.addClass("selected");
}

html:

<div class="initialclass" onclick="choose()">CLICK</div>

I have other javascript commands in that function that are working properly I just can't get the class to add.

Upvotes: 2

Views: 13661

Answers (4)

Tushar
Tushar

Reputation: 87203

Use classList:

classList returns a token list of the class attribute of the element.

el.classList.add("selected");

classList.add:

Adds a class to an element's list of classes. If class already exists in the element's list of classes, it will not add the class again.

CODE

HTML:

<div class="initialclass" onclick="choose(this)">CLICK</div>

Javascript:

function choose(el) {
    el.classList.add("selected");
}

DEMO

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337626

You have two issues with your current code. First is that this in your JS function refers to the window, not the element that was clicked. Second if it did refer to that element, it would be a DOMElement, not a jQuery object, so it would not have the addClass() method - you need to convert it to a jQuery object. Try this:

<div class="initialclass" onclick="choose(this)">CLICK</div>
function choose(el) {
    $(el).addClass("selected");
}

Note however, that it is better practice to hook up your events using JavaScript. As you are using jQuery, you can do this:

<div class="initialclass">CLICK</div>
$(function() {
    $('.initialclass').click(function() {
        $(this).addClass("selected");
    });
});

Upvotes: 8

Umesh Sehta
Umesh Sehta

Reputation: 10683

change your html like this:-

<div class="initialclass" onclick="choose(this)">CLICK</div>

and function:-

function choose(dv) {
   $(dv).addClass("selected");
 }

Upvotes: 2

Varun
Varun

Reputation: 1946

If you use jquery add this is code in your $(document).ready()

$(".initialclass").click(function(){
   $(this).addClass("selected");

});

Upvotes: 1

Related Questions