javascript - need suggestions with getting specific elements from container
hi,
here is what i want to do:
e.g.
Code:
<div id="container">
<h1>text</h1>
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
<random tag></<random tag>>
.
.
.
<h1>text</h1>
<p>text</p>
<p>text</p>
.
.
.
</div>
i want to get list of all h1 and p, but i need to preserve order e.g h1pppppppph1ppppph1pp,
i can do this by getting all elements and then check if element.tagName == "h1" but this way i will check hundreds of elements that i dont need while getting only few h1 and p, is there a way to optimize it, or maybe better approach ?
Re: javascript - need suggestions with getting specific elements from container
You are correct about the method, but I think you are confused as to how easy, and few lines of code, it is.
Code:
var output = "";
var elms = document.getElementsByTagName("*");
for (var i = 0; i < elms.length; i++) {
if (elms[i].tagName == "h1") {output += "h1"}
if (elms[i].tagName == "p") {output += "p"}
}
alert(output);
Re: javascript - need suggestions with getting specific elements from container
first and last optimization - skip some for loop iterations -when i am sure i wont omit h1 or p - DONE