GUIDE: Basic DOM Manipulation

❯❯ Modifying Styles Of Programmatically Created Elements

If we create element nodes programmatically in javascript, then we must set their style programmatically directly using the style property.

Create an element node and set its color and background color
click to copy code segment
const newDiv = document.createElement("div");
newDiv.style.color = "red";
newDiv.style.backgroundColor = "grey";

                              

❯❯ Modifying Styles And Attributes of DOM Rendered Elements

If elements were created by the markup (using HTML5) and styles using CSS3, prior to javascript manipulating the DOM, we use a function that grabs the generated style, which is a method of the window object.

Assuming div1 was rendered from HTML markup and CSS styling, grab its width and height and modify them
click to copy code segment
const div1 = document.querySelector(".box");
const div1Style = getComputedStyle(div1);
div1.style.width = parseFloat(div1Style.width) + 100 + "px";
div1.style.height = parseFloat(div1Style.height) + 100 + "px";

                              

If the rendered elements have attributes attached to them we can grab them and modify them, or we can generate an attribute to an existing element node programmatically

Change and set attributes of an element node in the DOM
click to copy code segment
const link = document.querySelector(".website");
const websiteAddr = link.getAttribute("href");
const newWebsiteAddr = "https://www.example.com";
link.setAttribute("href", newWebsiteAddr);

                              

❯❯ Modifying CSS Vars

In CSS3 we can use variables (for value reusability and facilitating consistent design) of the form 'property: var(properyName, propertyValue)'. Usually the properyName is written in the form --div-color (for example).

Get and set a CSS3 variable property of a rendered DOM element
click to copy code segment
const div2 = document.querySelector(".box2");
const div2Color = div2.getProperty("--div-color");
div2Color.setProperty("--div-color", "#661670");

                              

profile picture

WHO AM I?

Teacher
Thinker
Tinkerer