Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  171] [ 7]  / answers: 1 / hits: 36193  / 13 Years ago, thu, september 8, 2011, 12:00:00

How does one select DOM elements in javascript?

Like for example:



<div class=des>
<h1>Test</h1>
<div class=desleft>
<p>Lorem Ipsum.</p>
</div>
<div class=Right>
<button>Test</button>
</div>
</div>


Now how do i select h1? This is just a part of a bigger Page, so cannot use getElementsByTagName(), since others might get selected. Also since there might be other h1's in the document later, i cannot attach the index(body's) to above.



Is there a simple way to select, say <h1> tag which is under the classname of desleft?
I cannot use jQuery or any other libraries.


More From » dom

 Answers
51
getElementsByTag()


Would be a function that you can start with, and then you can filter for the DOMElements that have the class.



var h1_array = document.getElementsByTag('h1');

var h1_class_array = [];
for (var i=0, len=h1_array.length; i < len; i++) {
if (h1_array[i].className.indexOf('classname') !== -1) {
h1_class_array.push(h1_array[i]);
}
}


The .indexOf function returns -1 if the needle is not found in the haystack.



Now re-reading your question, why not just give your h1's id's ?



DOM traversal is one of javascript's glaring issues (enter jQuery).



a simple getElementById() would save you a headache, and ids on all your h1's would be much cleaner in the end than trying to formulate an algorithm to select them by other means.


[#90198] Wednesday, September 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;