Introduction to the DOM
Navigating these links among parents, children, and siblings is often useful. But if we want to find a specific node in the document, reaching it by starting at document.body
and following a fixed path of properties
is a bad idea. Doing so bakes assumptions into our program about the precise structure of the document – a structure you might want to change later. Another complicating factor is that text nodes are created even for the whitespace between nodes. The
example document's <body>
tag does not have just three children (<h1>
and two <p>
elements) but actually
has seven: those three, plus the spaces before, after, and between them.
So if we want to get the href
attribute of the link in that document, we don't want to
say something like "Get the second child of the sixth child of the document body". It'd be better if we could say "Get the first link in the document". And we can.
let link = document.body.getElementsByTagName("a")[0]; console.log(link.href);
All element nodes have a getElementsByTagName
method, which collects all elements with the given tag name that are descendants (direct or indirect children) of that node and returns them as an array-like object.
To find a specific single node, you can give it an id
attribute and use document.
instead.
<p>My ostrich Gertrude:</p> <p><img id="gertrude" src="img/ostrich.png"></p> <script> let ostrich = document.getElementById("gertrude"); console.log(ostrich.src); </script>
A third, similar method is getElementsByClassName
, which, like getElementsByTagName
, searches through the contents of an element node and retrieves all elements that have the
given string in their class
attribute.