简体   繁体   中英

Javascript search for tag and get it's innerHTML

It's probably something really simple, but I'm just learning.

There's a page with 3 blockquote tags on it, and I'd need to get the innerHTML of the one containing a certain string. I don't know how to search/match a string and get the innerHTML of the tag containing the matched result.

Any help would be appreciated!

var searchString = 'The stuff in innerHTML';
var elements = document.getElementsByTagName('blockquote')
for (var i = 0; i < elements.length; i++) {
     if (elements[i].innerHTML.indexOf(searchString) !== -1) {
         alert('Match');
         break;
     }
}

:)

Btw there would be a much nicer method if you'd be using Prorotype JS (which is much better than jQuery btw):

var el = $$('blockquote').find(function(el) {
    return el.innerHTML.indexOf('The string you are looking for.') !== -1;
});

You could of course also use regular expressions to find the string, which might be more useful (use el.match() for that).

If you need to search through every <blockquote> on the page, try this:

function findBlockquoteContainingHtml(matchString) {
    var blockquoteElements = document.getElementsByTagName('BLOCKQUOTE');
    var i;
    for (i = 0; i < blockquoteElements.length; i++) {
        if (blockquoteElements[i].innerHTML.indexOf(matchString) >= 0) {
            return blockquoteElements[i].innerHTML;
        }
    }
    return null;
}

Assign an id to the blockquote elements then you can get the innerHTML like this:

HTML:

<blockquote id="bq1">Foo</blockquote>

JS:

var quote1 = document.getElementById('bq1').innerHTML;

Be careful using innerHTML to search for text within a tag, as that may also search for text in attributes or tags as well.

You can find all blockquote elements using:

var elems = document.getElementsByTagName("blockquote")

You can then look through their innerHTML , but I would recommend instead looking through their textContent / innerText (sadly, this is not standardized across browser, it seems):

for (i in elems) {
  var text = elems[i].textContent || elems[i].innerText;
  if (text.match(/foo/)) {
    alert(elems[i].innerHTML);
  }
}

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