[英]How to get an array of elements which have an attribute attr with value val
[英]Is it possible to get all elements which have a specific value into any type of attribute?
我想获取 HTML Dom 中的所有元素,这些元素具有具有特定值的任何属性。
例如 -
<ul style="width:150px;" id="RadioButton1">
<li style="width:150px;"><input type="radio" name="RadioButton1"><label>Option 1</label></li>
<li style="width:150px;"><input type="radio" name="RadioButton1"><label>Option 2</label></li>
<li style="width:150px;"><input type="radio" name="RadioButton1"><label>Option 3</label> </li>
</ul>
我想获取任何属性中包含“RadioButton1”的所有元素。 意味着我想选择UL
和所有三个RadioButtons
。
注意:上面的 HTML 使用了UL-LI
结构,但实际情况相差太大。 所以请不要给出完全赞成UL-LI
答案。 我想要全球解决方案。
是否存在任何选择器来选择所有类型的属性?
是否可以在这种方法中选择元素?
提前致谢...!!!
可以通过过滤每个元素并检查其属性来完成:
var elements = $('*').filter(function () {
return $(this.attributes).filter(function(){
return this.nodeValue == 'RadioButton1';
}).length;
});
尝试这个:
$("*").each(function() { //check all elements inside DOM
var elem = $(this);
$.each(this.attributes, function() {
if(this.value=='RadioButton1'){
console.log(elem); //your code goes here. elem is nothing but element
//with value RadioButton1 in any attribute
}
});
});
注意:检查控制台的元素。
attributes 属性包含所有这些:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
if(this.value == 'RadioButton1')
{
alert(this.name);
}
}
});
});
$("input[name='RadioButton1'],ul[id='RadioButton1']")
$('[name="RadioButton1"]')
将选择所有具有“RadioButton1”作为其name
属性的项目。
$('[id="RadioButton1"]')
将选择所有具有“RadioButton1”作为其id
属性的项目。 请记住,对于 ID 属性,应该只有一个具有任何给定 ID 的项目。
$('[name="RadioButton1"],[id="RadioButton1"]')
会给你组合列表。
请记住,将 ID 和 Name 属性都设置为“RadioButton1”的项目将被添加两次。
如果您要搜索第三个属性,只需将该属性添加到以逗号分隔的选择器列表中。
为此,您应该使用 data-types="RadioButton"
然后使用
$('input[data-types=RadioButton]')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.