For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
Thanks!
Here I get the H1 elements value in a div where the H1 element which has CSS class="myheader":
Here is the markup:
I would also recommend to use jQuery if you need a heavy parsing for your DOM.
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on
descendants
to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):
Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.
To get the children nodes, use
obj.childNodes
, that returns a collection object.To get the first child, use
list[0]
, that returns a node.So the complete code should be:
If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the
className
attribute.The code should be:
The simplest way of doing it with your current markup is:
document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';
This assumes your H1 tag is always the first one within the
'header-inner'
element.If you are sure that there is only one H1 element in your div:
Going through descendants,as Shog9 showed, is a good way too.