Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 452
Kevin Lloyd Bernal Avatar asked Sep 28 '13 15:09

Kevin Lloyd Bernal


People also ask

How do I add a class to a div?

Step 1) Add HTML:Add a class name to the div element with id="myDIV" (in this example we use a button to add the class).

How do I add a class to a dynamic element?

To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript. Approach: The className property used to add a class in JavaScript.

How can you add a new My class class to an element using JavaScript?

Using . add() method: This method is used to add a class name to the selected element. Syntax: element.


1 Answers

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

like image 187
Tushar Gupta - curioustushar Avatar answered Sep 16 '22 18:09

Tushar Gupta - curioustushar