How to Get Element by Innertext

How to get element by innerText

You'll have to traverse by hand.

var aTags = document.getElementsByTagName("a");
var searchText = "SearchingText";
var found;

for (var i = 0; i < aTags.length; i++) {
if (aTags[i].textContent == searchText) {
found = aTags[i];
break;
}
}

// Use `found`.

Javascript - get element id by inner text

If you can get a reference to a descendant element, then you can use the .closest() method:

// Get all the span elements and loop through themdocument.querySelectorAll("span").forEach(function(element){  // Check the textContent of the element for a match  if(element.textContent === "persistant text"){    // Find the nearest ancestor div    let closest = element.closest("div")    // ...then do whatever you want with it    console.log("The " + closest.nodeName + " has an id of: " + closest.id);  }});
<div id="unpredictable-id1">    <label>        <span id="unpredictable-id1"> (unpredictable text) </span> <!-- this span have has the same id than div but has unpredictable content -->        <span>persistant text</span> <!-- this span have no id, no class, no identifier -->    </label></div>

selecting element based on innertext javascript

While I'm unsure of the logic behind the requirements I believe the following code seems to do what you ask:

// declaring a named function that takes two arguments:
// selector: String, a CSS selector to determine the elements you're trying to search,
// needle: String, a string of text that you're searching for to identify a given element:
const findElementByText = (selector, needle) => {

// here we convert the iterable NodeList returned from document.querySelectorAll()
// into an Array, using the Array.prototype.from() method:
return Array.from(
// we pass the 'selector' argument to document.querySelectorAll()
// to find all matching elements within the document:
document.querySelectorAll(selector)
// we then filter the resulting Array, using Array.prototype.filter()
// which retains, or discards, Array-elements based on truthy/falsey
// results of assessments within:
).filter(
// using the anonymous Arrow function, we retrieve the childNodes of
// each found element-node returned from document.querySelectorAll(),
// 'el' is a reference to the current element-node of the Array of
// element-nodes over which we're iterating:
(el) => {
// here we declare a variable, converting the HTMLCollection returned
// by Node.childNodes into an Array of nodes in order to use Array-
// methods such as Array.prototype.some():
let children = Array.from(el.childNodes);

// we use Array.prototype.some() to test if some of the Array-elements
// match the supplied tests; if so the method returns a Boolean true
// otherwise, if no Array-element matches, it returns a Boolean false:
return children.some(
// here we use the anonymous Arrow function, and we check that some
// of the childNodes (referenced as 'child' within the function body)
// are of nodeType === 3 (a textNode) and that the childNode's nodeValue
// once trimmed of leading/trailing whitespace is equal to the
// supplied String:
(child) => child.nodeType === 3 && child.nodeValue.trim() === needle
);
// here we use Array.prototype.map() to construct a new Array based on
// the Array-elements retained by Array.prototype.filter():
}).map(
// again, using an anonymous Arrow function, passing a reference to
// the current element-node into the function:
// first we create an Array from the iterable HTMLCollection of the
// current element-node's children:
(el) => Array.from(
el.children
// we then use Array.prototype.map() to create a new Array
// based on those childNodes:
).map(
// here we create another Array from the children of the
// previous child (since you seem to explicitly want the
// child-elements of the <span> in your posted code:
(child) => Array.from(child.children)
// we then use Array.prototype.flat() to collapse the Array
// to only one-dimension:
).flat()
// and then again, we use Array.prototype.map() to map the
// textContent of each child:
.map(
(child) => child.textContent.trim()
// and finally we flatten the multidimensional Array:
).flat()
).flat();
};

console.log(findElementByText('div', 'div-1'));
*,
::before,
::after {
box-sizing: border-box;
font-size: 1rem;
line-height: 1.5;
margin: 0;
padding: 0;
}

div,
span {
border: 1px solid var(--indicator);
display: block;
width: 90%;
margin: 0.2em auto;
}

div {
--indicator: lime;
}

span {
--indicator: lightblue;
}
<div>div-1
<span>div-1-span-1
<div>div-1-span-1-div</div>
<span>div-1-span-1-span</span>
</span>
</div>

Javascript .querySelector find div by innerTEXT

OP's question is about plain JavaScript and not jQuery.
Although there are plenty of answers and I like @Pawan Nogariya answer, please check this alternative out.

You can use XPATH in JavaScript. More info on the MDN article here.

The document.evaluate() method evaluates an XPATH query/expression. So you can pass XPATH expressions there, traverse into the HTML document and locate the desired element.

In XPATH you can select an element, by the text node like the following, whch gets the div that has the following text node.

//div[text()="Hello World"]

To get an element that contains some text use the following:

//div[contains(., 'Hello')]

The contains() method in XPATH takes a node as first parameter and the text to search for as second parameter.

Check this plunk here, this is an example use of XPATH in JavaScript

Here is a code snippet:

var headings = document.evaluate("//h1[contains(., 'Hello')]", document, null, XPathResult.ANY_TYPE, null );
var thisHeading = headings.iterateNext();

console.log(thisHeading); // Prints the html element in console
console.log(thisHeading.textContent); // prints the text content in console

thisHeading.innerHTML += "<br />Modified contents";

As you can see, I can grab the HTML element and modify it as I like.

How to get only directly contained text in DOM element in Javascript?

.clone() clones the selected element.

.children() selects the children from the cloned element

.remove() removes the previously selected children

.end() selects the selected element again

.text() gets the text from the element without children

const elementText = $("#price").clone()                                .children()                                .remove()                                .end()                                .text();
console.log(elementText.trim().split("\n")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="parent">  Parent  <span>Child 1</span>  <span>Child 2</span></div>
<div id="price"> 100$ <span>some ads</span> <span>another ads</span> for each</div>

How to get a innerText based on class name?

use document.getElementsByClassName("helloh")[0].innerText instead of document.getElementsByClassName("helloh").innerText.
When using getElementsByClassName, you will get array of elements instead of single array unlike getElementById.



Related Topics



Leave a reply



Submit