简体   繁体   English

从属性中获取值为“ xyz”的HTML标签

[英]Get HTML tag from Attribute having value “xyz”

i have a html tag as below (no id or class defined): 我有一个html标记,如下所示(未定义idclass ):
<a href="#" letter="xyz">All</a>

i need to get the tag having attribute value='xyz' 我需要获取具有属性值='xyz'的标签
i was successful in finding the attribute by: 我通过以下方式成功找到了属性:

var html_tag = $("a").find('[letter="xyz"]');
but it returns an object. 但它返回一个对象。

i need to get html tag so that i can use it as: 我需要获取html标记,以便可以将其用作:
$(html_tag).css('color','#FFFFFF');

Or suggest me any other solution if this is not possible. 或建议我任何其他解决方案,如果不可能的话。

$("a").find('[letter="xyz"]') will find descendants of anchor with attribute value letter="xyz" $("a").find('[letter="xyz"]')将找到属性值为letter="xyz"的锚的后代

You need to use Attribute Equals Selector [name=”value”] with anchor tag 您需要使用带有锚标记的Attribute Equals Selector [name =” value”]

Selects elements that have the specified attribute with a value exactly equal to a certain value. 选择具有指定属性且其值与特定值完全相等的元素。

Use 采用

$('a[letter="xyz"]').css('color','#FFFFFF');

You could also use .filter() 您也可以使用.filter()

Reduce the set of matched elements to those that match the selector or pass the function's test. 将匹配元素的集合减少到与选择器匹配或通过功能测试的元素。

$("a").filter('[letter="xyz"]').css('color','#FFFFFF');

Your code is trying to find element in anchor element that have letter attr equal to xyz. 您的代码正在尝试在锚定元素中找到字母attr等于xyz的元素。 which do not exists. 不存在。 Using .filter() instead of .find() would solve the problem. 使用.filter()代替.find()将解决此问题。

However you can simply use: 但是,您可以简单地使用:

var html_tag = $('a[letter="xyz"]');

Note: you should use .data-* attributes(added in HTML5) for adding custom attributes as adding your own attributes can break elements validation and make html invalid (see https://stackoverflow.com/a/1735239/1719752 ). 注意:您应该使用.data-*属性(在HTML5中添加)来添加自定义属性,因为添加自己的属性可能会破坏元素验证并使html无效(请参阅https://stackoverflow.com/a/1735239/1719752 )。

使用以下代码

var anchorTag = $('a[letter="xyz"]');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM