Kevin Lloyd Bernal
Kevin Lloyd Bernal

Reputation: 363

javascript add class to an element in a specific div

So I have this arrangement in my page:

<div class="food">

    <div>
        <a href="#" class></a>
        <a href="#" class></a>
    </div>

    <div>
        <a href="#" class></a>
        <a href="#" class></a>
    </div>

</div>

How do I add a class to all the a elements inside my div.food? What is the shortest and quickest way to implement this?

Thanks!

Upvotes: 5

Views: 32105

Answers (4)

To add class to all a tag in div with class food

$('div.food a').addClass('className');

or

As commented by A. Wolff .find() is faster

$('div.food').find('a').addClass('className');

or

To add class to all elements in div with class food

$('div.food *').addClass('className');

or

$('div.food').find('*').addClass('className');

.addClass()

.find()

also read .removeClass()

Upvotes: 18

Suresh
Suresh

Reputation: 59

Add a class in specific div:

$("#divData").addClass("className");

Remove a class in specific div:

$( "#divData" ).removeClass( "className" );

Upvotes: 0

mindfullsilence
mindfullsilence

Reputation: 452

If you don't want to use jQuery:

var links = document.querySelectorAll('.food a');
[].forEach.call(links, function(item) {
  item.classList.add('myClass');
});

Upvotes: 2

lvarayut
lvarayut

Reputation: 15259

JQuery comes with addClass() and removeClass() to add or remove CSS class dynamically. For example,

$(‘.food′).addClass(‘ClassName’); – Add a “ClassName’ css class to elements that contain class of food

If you want to remove a class from your div, you can use the following:

$(‘.food′).removeClass(‘ClassName’); - Remove a “ClassName’ css class from elements that contain class of food

Upvotes: 2

Related Questions