Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element by innerText

How to get tag in html page, if I know what text tag contains. E.g.:

<a ...>SearchingText</a> 
like image 903
Anton Kandybo Avatar asked Sep 28 '10 13:09

Anton Kandybo


People also ask

How do I get text content of an element?

To find elements by content:Use the document. querySelectorAll method to select DOM elements by tag. Use the for...of loop to iterate over the collection. On each iteration, check if the textContent of the element matches the expected content.

What does the innerText give you?

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

How do I get an element from innerHTML?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.


2 Answers

You could use xpath to accomplish this

var xpath = "//a[text()='SearchingText']"; var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; 

You can also search of an element containing some text using this xpath:

var xpath = "//a[contains(text(),'Searching')]"; 
like image 187
carlin.scott Avatar answered Sep 20 '22 06:09

carlin.scott


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`. 
like image 23
August Lilleaas Avatar answered Sep 18 '22 06:09

August Lilleaas