Reputation: 385
I have a particular div class in which there is anchor tag with no class and i have to add class to it using jquery. This is sample html
<div id="mydiv"><a href="www.google.com">myclass</a></div>
This is what i am trying but not working
$('.myclass','a').attr('class','myclass');
Thanks in advance.
Upvotes: 4
Views: 50384
Reputation: 82241
You need to use .addClass()
:
$('#mydiv a').addClass('myclass');
Upvotes: 10
Reputation: 73906
You can do this:
$('#mydiv > a').addClass('myclass');
mydiv
.addClass()
method.In case, the anchor is not a direct child of mydiv
, you can do this:
$('#mydiv a').addClass('myclass');
Your code:-
$('.myclass','a').attr('class','myclass');
didn't worked since, you're actually trying to find the myclass
inside a anchor tag. So, the above code actually means:-
$('a').find('.myclass').attr('class','myclass');
or ( in case, you have typo )
$('a').find('#mydiv').attr('class','myclass');
Upvotes: 1
Reputation: 22721
Can you try this,
$('#mydiv a').attr('class','myclass');
Or:
$('#mydiv a').addClass('myclass');
Upvotes: 0
Reputation: 15699
mydiv
is an id. Id is referred as #id
in jQuery.
find()
method allows us to search through the descendants of the elements in the DOM tree.
addClass()
adds the specified class(es) to each of the set of matched elements.
$("#mydiv").find("a").addClass("myclass");
Upvotes: 2
Reputation: 133403
You can use .addClass()
$('#mydiv a').addClass('myclass');
$('#mydiv').find('a').addClass('myclass');
Upvotes: 4
Reputation: 20418
Use .addClass()
.attr()
Try this
$('.myclass a').addClass('myclass') //Selector is class
$('.myclass a').attr('class','myclass');
In your page
$('#mydiv a').addClass('myclass'); //Selector is id
Upvotes: 0