简体   繁体   中英

How to get a HTML element by searching the content of innerHTML?

How to get a HTML element by searching the content of innerHTML?

For example, Search

I want to get the "a" tag by searching word "Search" using javascript.

Thank you

var aTags = document.querySelectorAll('a');    
var searchaTag = '';
    for(i = 0; i<aTags.length; i++ ) {
    if(aTags[i].text == 'Search') {
     searchaTag = aTags[i];
     break;
    }

    }

If you have no idea where the element can be, iterate over each element:

var all = document.querySelectorAll('*'); //OR document.getElementsByTagName("*")
for(var i = 0; i < all.length; i++ ) {
    if(all[i].innerHTML === "search") {
        console.log(all[i].tagName);
    }
}

If you have some clue you can narrow your search by looking inside that area:

var all = document.querySelector('#my-Container').getElementsByTagName('*');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM