Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 930
David R. Avatar asked Dec 30 '09 17:12

David R.


People also ask

How do I get the innerHTML element?

innerHTML. The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

How do I get innerHTML of a selected option?

getElementById ("select"); select. onchange = function () { alert (this. value); //returns the selected value alert (this. innerHTML); //returns the entire select with all the options var options = this.

How do I grab 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.

What are getElementById () and innerHTML properties?

innerHTML = 'Data or content'; getElementById: The getElementById refers to the HTML element using its ID. Data or content: Data is the new content to go into the element.


2 Answers

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

like image 115
watain Avatar answered Sep 18 '22 14:09

watain


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;
}
like image 37
easeout Avatar answered Sep 20 '22 14:09

easeout