【问题标题】:JQuery find elements by partial tagnameJQuery 通过部分标记名查找元素
【发布时间】:2016-05-17 15:42:08
【问题描述】:

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

例如,我想使用 JQuery 查找标记名中包含单词 directive 的所有元素。

<a-directive>...</a-directive>
<directive-b>...</directive-b>

我尝试了$("directive*")$("*directive")$("*directive*"),它们都不适合我。

我只在JQuery中找到了通过部分属性匹配来查找元素的方法,比如$("[name*='something']")

但找不到通过部分标记名查找元素的方法。

【问题讨论】:

  • 我要求您在投反对票之前添加评论,解释我的问题缺少什么。谢谢。
  • 两个问题。 1) 你为什么要创建自己的元素和 b) 你尝试了什么,为什么 css-selectors 标签?
  • @j08691 这是一个角应用程序,其标签名称包含单词directive,我想将它们全部获取以用于 UI 自动化目的。我尝试了不同的 JQuery 选择器,我知道并且还网上搜索通过部分标签名称选择,找不到答案,所以问了一个问题。
  • 你确定这个 UI 自动化的东西没有其他的角度方式吗? Angular 不是为直接 DOM 操作而设计的,就像 JQuery 一样。
  • 我投了反对票,因为你给了我们问题,但没有尝试自己做。

标签: javascript jquery html tags


【解决方案1】:

虽然 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>

【讨论】:

    【解决方案2】:

    这是一种使用 jQuery 创建自定义选择器的方法:

    (function( $ ) {
    
         function icontains(elem, tagName) {
             return elem.nodeName.toLowerCase().indexOf((tagName || "").toLowerCase() ) > -1;
         }
    
         $.expr.pseudos.tagNameContains = $.expr.createPseudo ?
         $.expr.createPseudo(function( tagName ) {
            return function(elem) {
                return icontains(elem, tagName);
            };
         }) :
    
         function(elem, i, match) {
             return icontains(elem, match[3]);
         };
    
    })(jQuery);
    

    然后,你会这样使用它:

    //searches entire DOM for elements with 'directive' in tag name
    $(':tagNameContains(directive)')  
    

    //searches under div.someClass for elements with 'directive' in tag name
    $('div.someClass :tagNameContains(directive)') 
    

    Source

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 1970-01-01
      • 2018-12-24
      • 2015-04-18
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多