Suppose your website’s DOM is done and rendered. However, we need create, update, display or hidden another HTML Element into this DOM Tree, but in an interactive way, of course using JavaScript. For example, showing a modal component how consequence of a user’s click, which could be an event.
So, create, get, update and hidden HTML Elements interactively is one of the duties of document object, because we pretend alter the DOM Tree. So, we must call document instance, that’s why is a convention to declare it in a variable, in order to use it easily.
const d = document ;
const newDiv = d.createElement("div")
However, is also valided in JavaScript, in se same line-code get the reference of the HTML Element and immediately do the next with it, for instance:
document.getElementById("myDiv").textContent = "Hello, world!";
1. Get a HTML Element.
This means, get the DOM reference of the element(s) target, there are several ways to do it, but first you need to know how to identify this HTML Element(s) into the DOM Tree. It could be through its valid CSS Selected using for example its class, id or tag type. See the following methods to get an HTML element(s) that is already in the DOM tree.
const d = document;
//ID must be unique in the DOM.
const myElment = d.getElementById(“id-myElmentHTML”);
//Returns the first Element within the document that matches the specified selector, or group of selectors.
const myElment = d.querySelector(“#myId” OR “.myClass”) ;
//Returns a NodeList representing a list of the document's elements that match the specified group of selectors.
const myElmentS = d.querySelectorAll(“#myId” OR “.myClass”) ;
//Returns a collection of all elements in the DOM with the specified class name(s), as a NodeList object.
const myElmentS = d.getElementsByClassName("class-names");
//Returns a collection of all elements in the DOM with the specified tag name, as a NodeList object.
const myElmentS = d.getElementsByTagName(“tag-name”);
Using getElementsByClassName("class-names"), getElementsByTagName(“tag-name”), you will get an array or collection of HTML Element from maybe differents content parents, but all these are related or matches by its classes or by being same tag type. In case of getElementsByClassName("center test"), it will return an array of HTML Element which have both clases ("center" and "test") at lest. Being an array you can access to its positions by its index like this: getElementsByClassName("class-names")[0].
2. Create a HTML Element.
There are several ways to create a new HTML Element, for example using the method createElement(“tag name”). Once the new HTML Element is created, if you need you can add it classes, id, attributes and so on. Look the code:
const d = document;
const newDiv = d.createElement(“div”);
newDiv.id = “my-new-div”;
newDiv.className = “my-class-css”; OR
newDiv.setAttribute(“class”, “my-another-class”);
newDiv.style.backgrountColor = “red”; OR
newDiv.setAttribute(“style”, “background-color”:“red”; “font-size”: “16px”);
However, in this point in the code, you just create a HTML Element, you have not inserted it into the DOM Tree, to accomplish that, you must know how to identify and get another node (adjacent or parent) as a reference to insert the new element into the DOM Tree. Let’s to learn some ways:
3. Adding a HTML Element to the DOM Tree.
There are many ways to do this, but we need select a node (adjacent or parent) as a reference to insert the new element into the DOM Tree.
3.1. Parent as a reference node to insert.
You must get the reference of the parent container node, through its valid CSS Selected using for example its class, id or type tag in this case we will use getElementById(‘the-id-of-parentElement’).
const d = document;
const newDiv = d.createElement(“div”);
const parentDiv = d.getElementById(“id-parent”);
//newDiv Will be The Last child of parentDiv
parentDiv.appendChild(newDiv);
parentDiv.insertAdjacentElement(“beforeend”, newDiv);
//newDiv will be the The First child of parentDiv
parentDiv.insertAdjacentElement(“afterbegin”, newDiv);
//anotherElementChild will be siblings of newDiv
parentDiv.insertBefore(newDiv, anotherElementChild);
//anotherElementChild will be Replace by newDiv
parentDiv.replaceChild (newDiv,anotherElementChild);
3.2. Siblings as a reference node to insert.
In this case, we’ll get a future sibling how reference, instead of its parent container. Again, first we must find it into the DOM Tree to use it.
const d = document;
const newDiv = d.createElement(“div”);
const siblingArticle = d.getElementById(“id-siblingArticle”);
//newDiv will be placed as The Previous of the reference sibling.
siblingArticle.insertAdjacentElement(“beforebegin”, newDiv);
// newDiv will be inserted as The Next of the reference sibling.
siblingArticle.insertAdjacentElement(“afterend”, newDiv);
4. Update a HTML Element.
When you get the reference of the HTML Element, which you want to update, you can do it adding attributes, classes, style and so on, through methods and properties, in the following way.
const d = document;
const divToUpdate = d.getElementById(“id-myDiv”); //Getting the reference of the element
//Adding it a class
divToUpdate.className = “my-class-css”; //OR
divToUpdate.setAttribute(“class”, “my-another-class”);
//Adding it an event listener.
divToUpdate.setAttribute(“onclick”, “handleEventFunction()”);
//Adding it style.
divToUpdate.style.backgrountColor = “red”; //OR
divToUpdate.setAttribute(“style”, “background-color”:“red”; “font-size”: “16px”);
//Adding it plain text content.
divToUpdate.textContent = “Lorem Ipsum has been….”
//Adding it HTML Element, to replace the existing content or to add new content.
divToUpdate.innerHTML = `< p > Hello ${data.name}< /p>`
Notece that you can add classes to a HTML Elements through many ways, but be aware of using the property .className = “my-class-css” or setAttribute(“class”, “my-another-class”) you'll overwrite all previosly classes setted to this HTML Element, and just keep this last added it.. However if you use this instruction: theElement.classList.add('new-class-name') you won't overwrite the classes previous, just it will be added it. Of course, there is a method to remove a class from a HTML Element theElement.classList.remove('new-class-name').
Who you see, you can set attributes to a HTML Element existing in the DOM throught setAttribute(“name-attribute”, “value-attribute”), but also, you can get the value of attributes from a HTML Element existing in the DOM, using the method getAttribute((“name-attribute”).
5. Show and hidden a HTML Element.
You can take control of the HTML Element visualization, through display property that belongs to style Attribute, which can receive several values. But, for now, to be visible the element the value of display must be block, to hidden it its values is node.
function toggleElement(elementId) {
const element = document.getElementById(elementId);
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
6. Remove a HTML Element.
If you want to remove a HTML Element from the DOM, instead of hidden it, you can do it using the method remove() or removeChild(element). Look the following code:
const element = document.getElementById("my-element");
element.remove();
const parent = document.getElementById("my-parent");
const child = document.getElementById("the-child");
parent.removeChild(child);