You are on page 1of 2

Accessing Dom Elements

Add & Delete Elements to the DOM


Get element by id

JavaScript DOM document.getElementById('id'); Access an element first


const ourElement = document.getElementById('ourelement');

CHEAT SHEET Get element by class


Using innerHTML
document.getElementsByClassName('className');
ourElement.innerHTML = “Appended from innnerHTML”;
Query selector
append as a child for an element
Overview document.querySelector('.classname');
ourElement.appendChild(htmlNode);
Query selector All
The Document Object Model (DOM) is the structural
document.querySelectorAll('.classname'); remove child from an element
representation of the HTML elements arranged in
ourElement.removeChild(htmlNode);
hierarchical way to display a webpage and also making it
easy to access and manipulate them.
Get Children or Parent Node replace child from an element
ourElement.removeChild(newElement, oldElement);
Access child node
const element = document.getElementById('id'); Insert before or after an element
element.childNode; ourElement.insertAdjacentHTML("beforeend", htmlNode);

Access parent node


const element = document.getElementById('id');
element.parentNode;

beforebegin

Create new elements The HTML would be placed immediately before the element, as a sibling.

afterbegin
The HTML would be placed inside the element, before its first child.
creating an HTML element
beforeend
const ourElement = document.createElement('section'); The HTML would be placed inside the element, after its last child.

afterend
creating an text node The HTML would be placed immediately after the element, as a sibling.

const textNode = document.createTextNode('Hello');


JavaScript DOM Add / Modify CSS of an element
CHEAT SHEET 02 Access Element
const ourElement = document.getElementById('ourelement');

Add new style property


ourElement.style.color = “blue”;

remove a style
Access, Add, Remove Attributes ourElement.style.removeProperty("color");

An HTML element
Access all style list applied for this element
<a id=”ourelement” href=”#hello” >Hello</a>
ourElement.style; // returns an object

Access an element
const ourElement = document.getElementById('ourelement');

Check whether an attribute exist or not


ourElement.hasAttribute(‘href’); // returns true

Add new attribute


ourElement.setAttribute(‘target’, ‘_blank’);

Remove a exisiting attribute


ourElement.removeAttribute(‘target’);

You might also like