TIL
-
DOM - Document Object Model - object representation of the HTML code that is rendered on the browser.
-
The DOM consists of an outline or tree of nodes. The two types of nodes are text vs. element nodes.
-
way to traverse through an ancestor element -> element.closest(‘query’);
-
way to traverse through descendant elements -> element.querySelector(‘query’);
-
for going through child elements - you can also use
element.firstChild
,element.lastElementChild
, so on. note:firstChild
could also capture text nodes, whereasfirstElementChild
only captures element nodes. -
want to grab parent element -> element.parentElement;
-
examples of methods you can use to traverse through sibling elements ->
element.previousSibling
(this also does capture text nodes though),element.previousElementSibling
(this only captures element nodes),element.nextElementSibling
-
changing element’s innerHTML with this code
div.innerHTML = div.innerHTML + '<p> Something went wrong </p>'
is not best practice because this essentially re-renders the whole thing (not just rendering the newelement). Plus, if there is userinput within this element, that user input is lost.
-
to resolve this, you could use
div.insertAdjacentHTML('beforeend', '<p>Something went wrong</p>')
to simply add that new element — however, when you want direct access or want to reference this new element, you have to use querySelector method (which could be cumbersome). -
to resolve THIS secondary issue, you could use
const newP = document.createElement('p')
- you only use this ondocument
and thendiv.appendChild(newP);
-
to add a child before the first child of the element - use
Element.prepend()
; -
MAKE SURE TO CHECK MDN - to see browser compatibility for these methods (e.g. prepend vs. before);