javascript add class to an element in a specific div

29,841

Solution 1

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()

Solution 2

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

Solution 3

If you don't want to use jQuery:

var links = document.querySelectorAll('.food a');
[].forEach.call(links, function(item) {
  item.classList.add('myClass');
});
Share:
29,841
Kevin Lloyd Bernal
Author by

Kevin Lloyd Bernal

Updated on March 09, 2020

Comments

  • Kevin Lloyd Bernal
    Kevin Lloyd Bernal over 4 years

    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!

  • nkkollaw
    nkkollaw over 10 years
    Is jQuery becoming synonym with Javascript..? I was talking to a dev I'm working with yesterday, I said that since we're merely using jQuery for DOM selection, we could remove it to remove a dependency, and he basically implied I was crazy for even proposing not using jQuery... (not criticizing your response, just a question)
  • A. Wolff
    A. Wolff over 10 years
    .find() is supposed to be a little bit faster, if it's what mean OP by 'quickest': jsperf.com/find-vs-descendant-selector/36
  • A. Wolff
    A. Wolff over 10 years
    @nbrogi you are right, OP tagged with jQuery so we all presume he accepts jQuery as a solution but a javascript one would be faster for sure
  • lvarayut
    lvarayut over 10 years
    @nbrogi No, JQuery is not the synonym of Javascript. JavaScript is a language. jQuery is a library built with JavaScript. It includes many common web tasks to help developing websites. So, you can use javascript instead of JQuery, if you prefer. However, most of the time, JQuery is more convenient.
  • nkkollaw
    nkkollaw over 10 years
    @A. Wolff Oh, yeah definitely, was just wondering in general, more that regarding the response itself.
  • nkkollaw
    nkkollaw over 10 years
    @Holmes: I know, just speaking figuratively, that's why I wrote "is jQuery becoming", not "is it" ;-)