Bootcamp Notes – Day 20 (Tues) – The Dom (Document Object Model) – Part 3 (Locating Nodes)
The Dom – Locating Nodes
Four ways to locate nodes
Lets’s talk about locating nodes, based on this example code. Full code here at CodePen for locating nodes.
Notice that these statements in each of these function bodies start with a word document. Document in JavaScript references the HTML document that is running the code. It’s data type is that of an object. It is where we get the name DOM from, the document object model. The document object is itself considered to be a node in the DOM tree.
<h1>Locating Nodes Demo</h1>
<p id=”textToChange”>Click on a button to change the color of this text.</p>
<button type=”button” onclick=”changeColor1()”>Use DOM traversal</button>
<button type=”button” onclick=”changeColor2()”>Use getElementsByTagName</button>
<button type=”button” onclick=”changeColor3()”>Use getElementById</button>
<button type=”button” onclick=”changeColor4()”>Use querySelector</button>
We can access the style attribute of HTML elements by using .style after a given node in JS, this is called the style property. Most HTML element attributes (like .style.color) can be accessed in JavaScript by using properties in this way, not just the style.
For example we could do this in our code and it would hide the button instead.
document.querySelector(‘#textToChange’).style.color = ‘green’ // We change this line of code to…
document.querySelector(‘p + button’).hidden = true; //To this line….
Additional Resources:
- MDN – Document.getElementsByTagName()
- JavaScript.info – Searching: getElement*, querySelector*
- MDN – Locating DOM nodes using selectors – querySelector() and querySelectorAll()
- W3Schools – HTML DOM style property
- W3Schools – HTML DOM Element Object Properties and Methods
- MDN – HTMLElement Properties
- MDN – CSS Properties Reference