Today I learned...
Targeting Nodes with Selectors
<div id="container">
<div class="image"></div>
<div class="text"></div>
</div>
Use CSS-style selectors and relationship properties.
const container = document.querySelector('#container');
Use relationship selectors to identify a certain node based on its relationships to the other nodes around it.
console.dir(container.firstElementChild);
// select the first child of #container => image
DOM methods
Used to manipulate our webpage with JavaScript.
Query Selectors
Used to target nodes.
- element.querySelector(selector) returns reference to the first match of selector
- element.querySelectorAll(selectors) returns a “nodelist” containing references to all of the matches of the selectors
NOTE: For querySelectorAll, the return value is not an array, it’s really a “nodelist”. The nodelist can be converted into an array with Array.from() or the spread operator.
Element Creation
Creates a new element into memory (NOT INTO THE DOM).
- document.createElement(tagName, [options)
The element can be configured by altering the styles, classes, etc. before being added to the webpage. For example:
Append Elements
- parentNode.appendChild(childNode) appends childNode as the last child of parentNode
- parentNode.insertBefore(newNode, referenceNode) inserts newNode into parentNode before referenceNode
Remove Elements
- parentNode.removeChild(child) removes child from parentNode on the DOM and returns reference to child
Adding text content vs HTML content
div.textContent = "Hello World!";
// creates a text node and inserts it in div
div.innerHTML = "<span>Hello World!</span>";
// renders the html inside div
textContent is preferable for adding text. innerHTML should be used only if necessary because it can create security risks if misused. An example would be vulnerability to JavaScript injections explained in this video.
Top comments (2)
I have quickly gone over all your work up until this part, I am around here but I will fast forward till the end. I see am on track :) and its been interesting watching your journey too.
Nice! A fellow Odin Project student, I'm still going so not quite done yet but almost reaching the end. Thanks for reading!