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!
function findFirstDescendant(parent, tagname) { parent = document. getElementById(parent); var descendants = parent. getElementsByTagName(tagname); if ( descendants. length ) return descendants[0]; return null; } var header = findFirstDescendant("header-inner", "h1");
Only put required elements or attributes in HTML. You do not need to put ID attribute if it is not required, and you can always add ID attribute whenever required. Keeping only required elements in html will make it easy to read, clean, low on size and hence improves performance and speed.
Yes its in the official specification. You can have more than one element with the same id but it will invalidate your HTML and can cause other problems. You should only use an id once because its means to give you a unique reference to a element in the DOM which is very handy.
function findFirstDescendant(parent, tagname) { parent = document.getElementById(parent); var descendants = parent.getElementsByTagName(tagname); if ( descendants.length ) return descendants[0]; return null; } var header = findFirstDescendant("header-inner", "h1");
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):
var element = $('#header-inner h1');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With