LINGS LINGS - 6 months ago 19
HTML Question

JQuery find elements by partial tagname

I would like to find all elements on page by partial tagname.

For example, I would like to find all elements whose tagname contains the word

directive
using JQuery.

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


I tried
$("directive*")
,
$("*directive")
,
$("*directive*")
none of them worked for me.

I have only found a way in JQuery to find elements by partial attribute match, such as
$("[name*='something']")


But could not find a way to find elements by partial tagname.

Answer

Although jQuery has quite a range of selectors, I don't believe that they natively have support for targeting custom elements / tags.

Because of this, you would likely need to implement your own approach similar to the recommendation mentioned in 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);
});

Example

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>

Comments