javascript selectors
Solution 1
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.
Solution 2
You can use this to get to your H1:
var des = document.getElementsByClassName('des')
var fc = des[0].getElementsByTagName('h1')
alert(fc[0].innerHTML)
Solution 3
w3.org has selectors now (http://www.w3.org/TR/selectors-api/#examples). Here are 2 different ways that worked for me on Chrome. You may want to use querySelectorAll function that returns a list.
<script type="text/javascript">
//looks for <h1> tag under <div> with className "des"
showOff1 = function() {
var x = document.querySelector(".des h1");
alert(x.innerHTML);
}
//looks for <div> tag with className "desleft" and then use previousSibling to traceback <h1> tag
showOff2 = function() {
var y = document.querySelector("div.desleft");
var z = y.previousSibling.previousSibling;
alert(z.innerHTML);
}
</script>
<body onload="showOff2();">
Solution 4
Use querySelectorAll
You can use querySelectorAll
:
// Will return a NodeList even if there is only one element found
var heading = document.querySelectorAll('.des > h1');
heading[1].style.color = 'red'; // NodeList is similar to an array
This will return a NodeList.
or
Use querySelector
to return the first element found:
var first_heading = document.querySelector('.des > h1');
first_heading.style.color = 'blue';
Commonly used with an id selector #single-header-id
.
Solution 5
If you mean to select a h1
that is before the first element of class desleft
, you could always do this:
document.getElementsByClassName("desleft")[0].previousSibling.previousSibling
Example: http://jsfiddle.net/Xeon06/ZMJJk/
previousSibling
needs to be called twice because of the empty text node between the two. That's why using libraries to do this stuff is really the best way to go.
Aaditi Sharma
Updated on January 23, 2020Comments
-
Aaditi Sharma about 4 years
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 usegetElementsByTagName()
, since others might get selected. Also since there might be otherh1
'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 ofdesleft
? I cannot use jQuery or any other libraries. -
heisenberg over 12 yearsNote that this won't work on older versions of IE. (need IE9 at least I think) No jQuery is a real pisser when you're doing stuff like this, I've gotten so use to not worrying about DOM quirks.
-
Aaditi Sharma over 12 yearsThanks, that solves it :) However, out of curiosity, let's say i use it to find around 5 different elements, and since an array is created for each of <h1>, <p>, etc, etc, since there are a lot of <p> or other tags, the array will get pretty big. In real world scenario, will it consume a lot of memory/processing?
-
Aaditi Sharma over 12 yearsI've never used previousSibling before, will go through that, Thanks :)
-
Aaditi Sharma over 12 years@jondavidjohn : Thanks, did not know that. Back to more coding to find elements :/
-
jondavidjohn over 12 yearsObviously without a given limitation all scenarios will eventually get outside the realm of acceptable, but again, vanilla javascript DOM traversal is one of those things you just grin and bear.
-
Alex Turpin over 12 years@Aaditi, if you need to support older browsers and can't use a third-party library, I'd get ready to write a LOT more code.
-
Aaditi Sharma over 12 yearsWell <h1> is just for an example, I'll have to use it for other elements, was wondering if there was an easy and neat way to do DOM traversal using javascript. I guess, giving id's will have to be the smartest option, rather than increasing size and processing thanks just for traversals
-
jondavidjohn over 12 yearsyes, and this is exactly the issue that has given such popularity to the competing JavaScript libraries, as their primary function is DOM traversal and selection.
-
Wayne over 12 yearsBelieve it is being pushed as html5 (FF3, Chrome and Opera 9+) already support it.
-
Aaditi Sharma over 12 years@jondavidjohn : Guess, will just give id's to everything.That seems to be the way out.No sense in writing extra code for transversals, that too for extinct browsers :/