javascript - JQuery 通过部分标记名查找元素

标签 javascript jquery html tags

我想通过部分标记名查找页面上的所有元素。

例如,我想使用 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);
});

示例

enter image description here

<!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/

相关文章:

javascript - 非零值的 Google 图表趋势线

jquery - 如何从 magento 2 中的 Controller 获取 ajax 响应

javascript - 将 <ol> append 到 <div> 元素的 <li> 会导致恼人的错误

html - 背景图片网址

javascript - 如何从JavaScript中的字符串中提取值?

javascript - socket.io 无法在多个客户端上运行

javascript - 如何从 Jest 获取 JUnit XML 输出?

javascript - 谷歌柱形图更改栏颜色未动态设置

javascript - 多级列表中的大写首字母(JS、JQUERY)

php - 如何完成分页实现