Reputation: 33
When I try to add an attribute like id or class in html tags by using jQuery, then the old value of the attribute is lost.
Here is an example:
<div id="dom">
<h1 class="class">I am heading 1</h1>
<h1 class="class">I am heading 2</h1>
<h1 class="class">I am heading 3</h1>
<h1 class="class">I am heading 4</h1>
<h1 class="class">I am heading 5</h1>
<h1 class="class">I am heading 6</h1>
</div>
Now I am trying to add another class by jquery which has a class named 'class'.
<script>
$(document).ready(function(){
$('.class').attr('class','newClass')
})
</script>
As a result it removes the old class and set the new class. But I want both classes. What's a good way around this problem?
Upvotes: 3
Views: 136
Reputation: 87203
Problem:
When you use attr()
, jQuery will set the class
attribute value to newClass
, thus replacing all the previous classes.
Set one or more attributes for the set of matched elements.
Solution:
Use addClass()
to add a new class to the element.
Adds the specified class(es) to each element in the set of matched elements.
$('.class').addClass('newClass');
As I see, in your case, there is no need to use jQuery for adding a class on page load. You can do this in HTML.
Demo
$('.class').on('click', function() {
$(this).addClass('newClass');
});
.class {
color: red;
}
.newClass {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="dom">
<h1 class="class">I am heading 1</h1>
<h1 class="class">I am heading 2</h1>
<h1 class="class">I am heading 3</h1>
<h1 class="class">I am heading 4</h1>
<h1 class="class">I am heading 5</h1>
<h1 class="class">I am heading 6</h1>
</div>
Upvotes: 5
Reputation: 1306
When you will use attr() function than it will be replace with current attribute. You will use jquery addClass() method. It will helpfull for you.
$('.class').addClass('newClass')
Upvotes: 1
Reputation: 85545
Just use addClass():
$('.class').addClass('class-name');
Upvotes: 3
Reputation: 82231
.attr()
is used to get/set the new value. in case of set condition, the previous values associated to the attribute are completely overwritten by new ones.
You should use .addClass()
to add more class(es):
$('.class').addClass('newClass');
For adding multiple classes, separate multiple classes with the space in.addClass()
argument:
$('.class').addClass('newClass newclass2');
Upvotes: 6