Lesson 1: The DOM

Michelle Colón
The Road to React
Published in
3 min readApr 18, 2018

First up on Cassidy WilliamsUdemy course- a review of the DOM: what it is, what it can do, and the work-through for a common interview question. I usually take notes in bullet form- my brain likes that best.

DOM (Document Object Model)

  • The DOM is the bridge between JavaScript and HTML
  • The DOM is a tree, and each node (tree branch) is created from HTML tags
Source: https://www.cs.dartmouth.edu/~fwp/lecture06/Simple-Document-Tree.png
  • Typing document into the console shows the document object, but it is shown the same way it looks in the HTML
  • Typing console.dir(document) into the console will show us more JS-like properties
This is much more detailed!
  • How to create an element in the console:
var p = document.createElement('p') //this creates a p tagp.innerText = 'this is the created element' //this adds text to the tag<p>this is the created element</p> //this is the result when you type 'p' into the console
  • document.body.appendChild(p)will add the content of the p tag to the body

Common interview question: How would you implement getElementsByAttribute? (in layman’s: How to Find a DOM Node)

In steps, here’s what they’re asking you to do:

1. Get all of the elements in the DOM
2. Check if they have a particular attribute
3. Check that the attribute has the correct value

Here’s how you actually do it:

What the heck does this all mean?!

Line 1: The function takes in the assigned attribute and value parameters.

Line 2: Gets all of the elements in the DOM; The (‘*') is RegEx and it pulls in all the elements

Line 3: Initializes an empty array that will hold all of our found elements

Line 5: For loop that will go through all the elements

Line 7: For all the elements, check if getAttribute has the particular attribute (from in the parameter), and it if does have that attribute, check to see whether it equals the value (also from in the parameter)

Line 8: If the stuff from Line 7 is true, it pushes that element into the found array (that we created on Line 3); if it is false, it will keep going through the loop

Update 5/10/18: So! For Lines 7 & 8, it has come to my attention that I can replace the all[i] with element (since the variable is defined, but never used) and it will still work. I missed that when I originally posted this- thanks Todd Jones :)

All done with the DOM! Next time I will cover Events and Callbacks!

--

--