Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Custom Elements that start with a specified prefix

I have a bunch of Custom Elements that begin with 'food-cta-'. I am looking for a way in JavaScript/jQuery to be able to select these elements. This is similar to how I can use $('*[class^="food-cta-"]') to select all the classes that start with food-cta-. Is it possible to do a search for elements that start with 'food-cta-'?

Note that I will be injecting this search onto the page, so I won't have access to Angular.

Example of Custom Elements:

  • <food-cta-download>
  • <food-cta-external>
  • <food-cta-internal>

EDIT: The code I am looking at looks like:

<food-cta-download type="primary" description="Download Recipe">
    <img src="">
    <h2></h2>
    <p></p>
</food-cta-download>

The app uses AngularJS to create Custom Elements which I believe is called Directives.

like image 996
Jon Avatar asked May 31 '16 17:05

Jon


1 Answers

You can use XPath with the expression

 //*[starts-with(name(),'food-cta-')]

Where

  • //* is wildcard for all nodes
  • starts-with() is a XPath function to test a string starts with some value
  • name() gets the QName (node name)
  • and 'food-cta-' is the search term

Pass it into document.evaluate and you will get a XPathResult that will give you the nodes that were matched.

var result = document.evaluate( "//*[starts-with(name(),'food-cta-')]", document, null, XPathResult.ANY_TYPE, null );

Note you can use any node as the root, you do not need to use document. So you could for instance replace document with the some div:

var container = document.getElementById("#container");
var result = document.evaluate( "//*[starts-with(name(),'food-cta-')]", container, null, XPathResult.ANY_TYPE, null );

Demo

let result = document.evaluate( "//*[starts-with(name(),'food-cta-')]", document, null, XPathResult.ANY_TYPE, null );

let nodes = [];
let anode = null;

while( (anode = result.iterateNext()) ){
   nodes.push( anode.nodeName );
}

console.log(nodes);
<div id="container">
  <br>
  <food-cta-download type="primary" description="Download Recipe">
    <img src="">
    <h2></h2>
    <p></p>
  </food-cta-download>
  <span>Some span</span>
  <food-cta-something>
    <img src="">
    <h2></h2>
    <p></p>
  </food-cta-something>
  <div>In between
      <food-cta-sub>
         <img src="">
         <h2></h2>
         <p></p>
      </food-cta-sub>
  </div>
  <food-cta-hello>
    <img src="">
  </food-cta-hello>
  <food-cta-whattt>
  </food-cta-whattt>
</div>
like image 86
Patrick Evans Avatar answered Oct 05 '22 14:10

Patrick Evans