Megha Paul
Megha Paul

Reputation: 385

How to find anchor tag in div and add class?

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

Answers (6)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to use .addClass():

$('#mydiv a').addClass('myclass');

Working Fiddle

Upvotes: 10

palaѕн
palaѕн

Reputation: 73906

You can do this:

$('#mydiv > a').addClass('myclass'); 
  • This will find any child anchor inside the div with id mydiv
  • Then you can simply add a class to it using the jQuery .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

Krish R
Krish R

Reputation: 22721

Can you try this,

$('#mydiv  a').attr('class','myclass');

Or:

$('#mydiv  a').addClass('myclass');

Upvotes: 0

codingrose
codingrose

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

Satpal
Satpal

Reputation: 133403

You can use .addClass()

$('#mydiv a').addClass('myclass');

OR

$('#mydiv').find('a').addClass('myclass');

Upvotes: 4

Sridhar R
Sridhar R

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

Related Questions