User:Zuhui//Prototyping/Javascript
DOM
dev/ understanding dom nodes - a comprehensive guide with example
medium/ DOM manipulation part 1
medium/ DOM manipulation part 2
What is Document Object Model
- In simple words, DOM is the thing that gets generated after your browser parses the HTML that it gets.
- that thing is a tree structure that browsers use to understand and represent a web page.
- in this tree, each element is called a node.
- Document Node: This is the top-level node in the DOM and represents the entire HTML document.
- Element Node: This represents an HTML element, such as
div
,p
,ul
, etc. - Attribute Node: This represents an attribute of an HTML element, such as
id
,class
,src
, etc. - Text Node: This represents the actual text within an HTML element
- Comment Node: ?
so "manipulating the DOM" means modifying or exploring this tree structure of the web page.
directly and indirectly manipulating the DOM
example using DOM property and method to manipulate the contents in span elements
in this example, I used innerHTML
, innerText
, textContent
to add a space in between the spans. but didn't work(maybe only half-worked).
because they don't directly interact with the DOM tree but instead replace the entire content of an element.
- ↳ meaning, these DOM properties can modify content through strings without directly touching the DOM tree.
so basically what it did was wiped out the old content, replaced them with the string, created new nodes. that's why it looked like my spans were duplicating themselves.
I see that those can be immediately useful, but they are not sustainable in this case.
what worked, however, was DOM methods like appendChild()
createTextNode()
because DOM methods directly access and manipulate the DOM nodes. like adding, removing, or moving elements within the tree. like attaching, moving and cutting out branches.
when you're directly touching the tree, it keeps the existing structure intact while manipulating the elements.
NodeList and Array
Claudio and I suffered last time because we didn't know how to work these two together.
Difference between a NodeList and an Array in JavaScript
"A NodeList may look like an array, but they are two completely different things"
- NodeList(object): is a collection of DOM nodes extracted from the HTML document.
- Array: is a special data type in JavaScript that can store a collection of arbitrary elements.