javascriptinnertextselectors-api

Javascript .querySelector find <div> by innerTEXT


How can I find DIV with certain text? For example:

<div>
SomeText, text continues.
</div>

Trying to use something like this:

var text = document.querySelector('div[SomeText*]').innerTEXT;
alert(text);

But ofcourse it will not work. How can I do it?


Solution

  • 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.