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.
You can use XPath with the expression
//*[starts-with(name(),'food-cta-')]
Where
//*
is wildcard for all nodesstarts-with()
is a XPath function to test a string starts with some valuename()
gets the QName (node name)'food-cta-'
is the search termPass 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With