jQuery 如何在div中找到锚标签并添加类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20994445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:23:12  来源:igfitidea点击:

How to find anchor tag in div and add class?

jquery

提问by Megha Paul

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 类,其中有没有类的锚标记,我必须使用 jquery 向它添加类。这是示例 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.

提前致谢。

回答by Milind Anantwar

You need to use .addClass():

您需要使用.addClass()

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

Working Fiddle

工作小提琴

回答by Satpal

You can use .addClass()

您可以使用.addClass()

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

OR

或者

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

回答by Hiral

mydivis an id. Id is referred as #idin jQuery.

mydiv是一个id。Id#id在 jQuery 中被称为。

find()method allows us to search through the descendants of the elements in the DOM tree.

find()方法允许我们搜索 DOM 树中元素的后代。

addClass()adds the specified class(es) to each of the set of matched elements.

addClass()将指定的类添加到每个匹配元素集。

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

回答by pala?н

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.
  • 这将在带有 id 的 div 中找到任何子锚点 mydiv
  • 然后你可以简单地使用 jQuery.addClass()方法向它添加一个类。

In case, the anchor is not a direct child of mydiv, you can do this:

如果锚点不是 的直接子代mydiv,您可以这样做:

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

Your code:-

您的代码:-

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

didn't worked since, you're actually trying to find the myclassinside a anchor tag. So, the above code actually means:-

没有工作,因为你实际上是在试图找到myclass锚标签的内部。所以,上面的代码实际上意味着:-

$('a').find('.myclass').attr('class','myclass');

or ( in case, you have typo )

或(以防万一,您有错字)

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

回答by Sridhar R

Use .addClass().attr()

.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

回答by Krish R

Can you try this,

你可以试试这个吗

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

Or:

或者:

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