DOM Manipulation and Events
- The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage - a tree of “nodes” with different relationships depending on how they’re arranged in the HTML document.
-
Targeting Nodes with Selectors
- When working with the DOM, you use “selectors” to target the nodes you want to work with.
- You could use the following selectors to refer to
<div class="display"></div>
:- div.display
- .display
#container
> .display- div#container > div.display
-
DOM Methods
-
Query Selectors
element.querySelector(selector)
returns a reference to the first match of selector.element.querySelectorAll(selectors)
returns a “nodelist” containing references to all of the matches of the selectors.- It’s important to note that when using querySelectorAll, the return value is not an array. It looks like an array, and it somewhat acts like an array, but it’s really a “nodelist”.
- Several array methods are missing from nodelists.
- To convert nodelist into an array, we can use the Array.from() or the spread operator.
-
Element Creation
const div = document.createElement('div');
- This function does NOT put your new element into the DOM - it simply creates it in memory.
-
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 a reference to child.
-
Altering Elements
- When you have a reference to an element, you can use that reference to alter the element’s own properties.
const div = document.createElement('div'); // creates a new div referenced in the variable 'div'
- When you have a reference to an element, you can use that reference to alter the element’s own properties.
-
Adding Inline Style
div.style.color = 'blue'; // adds the indicated style rule div.style.cssText = 'color: blue; background: white;'; // adds several style rules div.setAttribute('style', 'color: blue; background: white;'); // adds several style rules
- See DOM Enlightenment’s section on CSS Style rules for more info on inline styles.
- Note that if you’re accessing a kebab-cased(each word separated with a dash character) CSS rule from JS, you’ll either need to use camelCase or you’ll need to use bracket notation instead of dot notation.
-
Editing Attributes
div.setAttribute('id', 'theDiv'); // if id exists, update it to 'theDiv', else create an id // with value "theDiv" div.getAttribute('id'); // returns value of specified attribute, in this case // "theDiv" div.removeAttribute('id'); // removes specified attribute
-
Working with Classes
div.classList.add('new'); // adds class "new" to your new div div.classList.remove('new'); // removes "new" class from div div.classList.toggle('active'); // if div doesn't have class "active" then add it, or if // it does, then remove it
-
Adding Text Content
div.textContent = 'Hello World!'
-
Adding HTML Content
- Note that textContent is preferable for adding text, and innerHTML should be used sparingly as it can create security risks if misused.
div.innerHTML = '<span>Hello World!</span>';
- Note that textContent is preferable for adding text, and innerHTML should be used sparingly as it can create security risks if misused.
- Try to understand the example below this code.
-
-
Events
- Events are actions that occur on your webpage such as mouse-clicks or keypresses, and using JavaScript we can make our webpage listen and react to these events.
-
Method 1
<button onclick="alert('Hello World')">Click Me</button>
-
Method 2
- HTML file:
<!-- the HTML file --> <button id="btn">Click Me</button>
- JS file:
// the JavaScript file const btn = document.querySelector('#btn'); btn.onclick = () => alert("Hello World");
- HTML file:
-
Method 3
- Method 3 is much more flexible and powerful, though it is a bit more complex to set up. Recommended.
- HTML file:
<button id="btn">Click Me Too</button>
- JS file:
const btn = document.querySelector('#btn'); btn.addEventListener('click', () => { alert("Hello World"); });
- With all three methods we can access more information about the event by passing a parameter to the function that we are calling. For example:
btn.addEventListener('click', function (e) { console.log(e); }); // 'function (e)' is a callback from addEventListener.
- The
e
in that function is an object that references the event itself. Within that object you have access to many useful properties and methods (functions that live inside an object) such as which mouse button or key was pressed, or information about the event’s target - the DOM node that was clicked.btn.addEventListener('click', function (e) { console.log(e.target); });