Events and dynamically updating the dom createElement, createTextNode etc Flashcards
How can I append a h1 element with class code to this?
<div>
<h2>Your class list is:</h2>
</div>
//put element we want to append to inside a variable.
const classListElement = document.getElementById(“classList”);
//THESE ARE CREATED INDEPENDENTLY
//create element inside the DOM
const createdClassCodeElement = document.createElement(‘h1’);
//adding text to the new element created.
const textOfClassCode = document.createTextNode(‘7X3’);
//append the new element and its text together
createdClassCodeElement.appendChild(textOfClassCode);
//append this into the existing DOM to h2 element with ID “classList”
classListElement.appendChild(createdClassCodeElement);
How can I create an element?
document.createElement(‘h1)
How can I create textContent?
document.createTextNode(‘ello’);
How can I append a createdElement and textNode?
put them inside variables,
e.g const createdElement
createdElement.appendChild(textNodeCreated)
What does insertBefore() do?
it allows you to insert an element and text if you want dynamically before an element
What do these two arguments mean?
insertBefore(‘element’, ‘location’)
element is the newly created element you want FIRST, the location is the one you want it to come SECOND or BEFORE)
Explain what is happening:
<div>
<h2>Kambanis</h2>
</div>
const surname = document.getElementById(“surname”);
const firstName = document.createElement(‘h1’);
const textOfFirstName = document.createTextNode(‘Laura’);
firstName.appendChild(textOfFirstName);
———-HERE——————-
surname.parentNode.insertBefore(firstName, surname);
the surname element has been put into a variable.
Then independently the new element has been created to document. and also its textNode.
They have been pushed together into the newly created element.
Now the original element is targeted, then the parentNode is specified, then insert before, then the firstName element is passed as an argument, then the surname (the original it will go before)
:)
Why do I need a parentElement and an element to put it before?
<div>
<h2>Kambanis</h2>
</div>
parentElement.insertBefore(firstName, targetElement)
The insertBefore() method needs to be called on the parent node of the element you want to insert.
The insertBefore() method is used to insert a new element as a child of a specified parent element.
This sounds counter-intuitive. But you are still specifying before which reference NODE, which is BEFORE.
SANDWHICH.