html - JavaScript find element by text -
I'm not in a single environment. I do not want to find tags or tags with some text. I DOM looks like this:
& lt; Div & gt; & Lt; Div & gt; & Lt; H2 & gt; Contains fixed text & lt; / H2 & gt; & Lt; / Div & gt; & Lt; Div & gt; & Lt; / Div & gt; & Lt; / Div & gt;
I am using XPath to find this div.
var linkBox = document.evaluate ('// h2 [in [text () text')] /../ .. ', document, blank, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, empty) < / Code>
This works fine unless I do not know that IE does not support XPath in the document. I am now getting the getElementsByTagname ('h2')
And then tell the entire set to check the inherent text.
Is there a better way to do this?
What is the lowest version of IE about Are you worried?
You may be able to use here to help reduce your search:
HTML
gt; & lt; h2 & gt; contains fixed text & lt; / h2 & gt; & lt; h2 & gt; ; Contains fixed text & lt; / h2 & gt; & lt; h2 & gt; yay & lt; / h2 & gt; & lt; h2 & gt; contains fixed text & lt; / h2 & gt; & Lt; / div & gt; & lt; Div & gt; & Lt; H2 & gt; Contains fixed text & lt; / H2 & gt; & Lt; H2 & gt; Contains fixed text & lt; / H2 & gt; & Lt; H2 & gt; Contains fixed text & lt; / H2 & gt; & Lt; / Div & gt; & Lt; / Div & gt; Javascript
// Turn on the nodellist in an array / feel free to use getElementsByTagName or something similar Do var h2 = Array.prototype.slice.call (document.querySelectorAll ("h2")); // match matches array = h2.filter (filterElements); Console.log (matching); // filter function function elements (element) {return element.textContent === "YAY"; }
A polyfill is on the Array.philter as well as the MDN page.
Comments
Post a Comment