June 20, 2013

addClass vs attr and creating an ID

Aaron’s Question:

So what I am reading is that when adding a class to an element without any class selectors, use the addClass() method over attr().

For example, using:

.addClass('myclass')

is more efficient than

.attr('class','myclass')

I cannot find anything equivalent to addId(‘myid’) for adding id selectors, does it exist or is attr() the best way to add an id selector?

I get that id is unique, the logic behind my question is addClass() is faster than attr().

So my question is if there’s a more efficient method for creating an id than attr().

Answering directly

No, addId() does not exist and addClass() is not as same as attr()

In HTML, a class attribute can hold more than one value like <div class="tall fat brown">Someone</div> so jQuery’s function addClass() helps to add a value to the class attribute not change it. Similarly the functions toggleClass() and ‘removeClass()` help manipulate them.

But the function attr() will just manipulate the attribute and change it directly.

For example:

<div id="person">someone</div>

And the following jQuery Statements

$("#div").addClass("tall"); // This will create the class attribute and add tall 
$("#div").addClass("fat");  // This will append fat to the existing class and make "tall fat"
$("#div").addClass("brown"); // likewise

.addClass() will just append the class name. If same needs to done by using attr() you have to do

$("#div").attr('class', 'tall');
$("#div").attr('class', 'tall fat');
$("#div").attr('class', 'tall fat brown');

Or, you can modify the attribute using

$("#div").attr('class', function(i, className) {
    return className + " brown";
});

Where as ids have one value that needs to be modified or altered so a function like addId() would do exactly which attr(‘id’, ‘idvalue’) would do.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!