我想通过部分标记名查找页面上的所有元素。
例如,我想使用 JQuery 查找标记名包含单词 directive
的所有元素。
<a-directive>...</a-directive>
<directive-b>...</directive-b>
我尝试了$("*directive*")
、$("*directive")
、$("*directive*")
他们都不适合我。
我只在JQuery中找到了一种通过部分属性匹配来查找元素的方法,例如$("[name*='something']")
但找不到通过部分标记名查找元素的方法。
最佳答案
尽管 jQuery 有相当多的 range of selectors ,我不相信它们本身就支持定位自定义元素/标签。
因此,您可能需要实现自己的方法,类似于this related discussion中提到的建议。 :
// Terribly inefficient approach (scope to parent element if at all possible
var directives = $("*").filter(function(){
// Return any elements that contains directive as the node name
return /^.*directive.*$/i.test(this.nodeName);
});
示例
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<a-directive>A</a-directive>
<div>Not A Directive</div>
<directive-b>B</directive-b>
<script>
$(function(){
var $directives = $("*").filter(function(){
// Return any elements that contains directive as the node name
return /^.*directive.*$/i.test(this.nodeName);
});
// Color your directives
$directives.css('color','red');
});
</script>
</body>
</html>
关于javascript - JQuery 通过部分标记名查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280772/