Nobody likes applications that are based on the console... Can you imagine using Uber from the command line?
1$ "uber" request-trip --from home-- to work --pool
Thankfully, we have browsers! They let us render our application in a visual interface that we call a website.
As you already know, the responsibility of the browser is to transform HTML/CSS code into visual elements. Those elements are mapped into a hierarchy that is stored in RAM memory, and it’s called The DOM.
With JavaScript we can manipulate the DOM (website elements) during runtime (the application's lifecycle).
NOTE: Please always remember that all JavaScript code that you write in your HTML document MUST be wrapped inside a <script>
tag, like this:
1<script type="text/javascript"> 2 // Your code here 3</script>
Nowadays, we tend to write all of our JS code in a separate file with extension .js
, in which case the script tag in your html's body needs to look like this:
1<body> 2 <div>some content</div> 3 <div>more content</div> 4 5 <script src="index.js" type="text/javascript"></script> 6</body>
This is the preferred way for you to write and link your JS code from now on, as well.
There are several ways to manipulate the DOM, but the most simple one is document.write()
. Every time you create a document.write()
you will be writing onto the HTML whatever string you decide to pass as a parameter to the write function.
It does not matter where you write the code. The only thing that matters is that it is linked to the HTML through a <script>
tag. For example:
From the moment a website starts being loaded, the browser creates a hierarchy that is called The DOM. Each HTML element you coded in your HTML document as a developer has a place in that hierarchy, and you can access it using JavaScript anytime you want during the runtime.
Just like we did with CSS, we can select any element in the document. There are various methods that allow us to target the element that we want. The most current methods are:
Returns an instance of the first element which matches the CSS selector that you specified.
Returns a list (similar to JavaScript array) with all elements which match the CSS selector.
It is preferable that you use these two methods in your work.
Other methods which are now considered deprecated but you may see in some code examples:
Returns an instance of the element with the id="elementId"
in the HTML document.
Returns an array of all elements with the class="exampleClass"
in their HTML tag property.
Returns an array with all the instances representing each paragraph element in the HTML document.
Returns an array with all the elements that have name="name_value"
in the name property of their HTML tag in the HTML document.
1let elem = document.getElementById("xyz"); 2elem.style.color = "red"; // change color to red 3 4let myList = document.getElementsByTagName("p"); 5let howManyElements = myList.length; 6myList[0].style.color = "red"; // make the first one red 7 8let myList = document.getElementsByClassName("abc"); 9myList[0].style.color = "red"; // make the first one red 10 11let xyz = document.getElementsByName("xyz"); 12xyz[0].style.color = "red"; // make the first one red
It is very common to need to change an element’s child. For example:
<li>
children of a specific <ul>
to make their background red.<tr>
row of a <table>
.The best way to retrieve the children elements of any DOM element is by using its .children
property, like this:
This returns an array with all the element’s children nodes.
Given the following example, open the code in JSFiddle and console.log tableElm.children
at the end of the existing JavaScript code:
Open the Console in the Chrome Inspector feature. What did you observe?
You should have gotten an array (HTMLCollection) with two items - the thead
and tbody
which are the table's direct children. Because you see that tableElm.children
gives you an array-like structure in JavaScript, you could guess that to get the first element (thead), you can simply code tableElm.children[0]
.
Now go to the end of the JS code and add another console.log - tableElm.children[1].children
.
Can you guess what this will return in the console? Try it out!
Here is an explanation of the other properties used in the example:
1x.querySelector(".random").style.background = "green"; 2// get the first #myDIV child with the .random class 3 4x.querySelector("h3,h2").style.background = "blue"; 5// get the first #myDIV child with the tag <h3> or <h2> 6 7let tableElm = document.querySelector("#people"); 8let trArray = tableElm.querySelectorAll("tr"); 9trArray[3].style.background = "red"; 10// get an array with all elements nested within the #people table, of type <tr> - not necessarily direct children
There are 2 functions we can use for that: appendChild()
and insertBefore()
.
Let's say that you have selected a <div>
with the id="myFirstDiv"
and you want to add a new <h1>
inside of that <div>
.
You can use the appendChild function like this:
1let divElem = document.querySelector("myFirstDiv"); 2let myNewHOne = document.createElement("h1"); 3let t = document.createTextNode("Hello World"); 4myNewHOne.appendChild(t); // This adds the text content to the <h1> 5divElem.appendChild(myNewHOne); // This adds the <h1> into the "myFirstDiv" element
Now, let's say that we have a <ul>
with 2 elements, but we want to insert a new <li>
at the beginning of that list.
We can use the function insertBefore
for that case – like this:
1... 2let newItem = document.createElement("li"); 3let textNode = document.createTextNode("Water"); 4newItem.appendChild(textNode); 5let list = document.getElementById("myList"); 6list.insertBefore(newItem, list.childNodes[0]); // adding the newItem before the FIRST child of the list
As you already know, each element in the HTML document can have some sort of HTML content. It does not matter if it is a <p>
, <div>
, <a>
or any other HTML element; it can have its own innerHTML combined with more HTML content.
The .innerHTML
property gives you the ability to retrieve or set the content of whatever element you have in your JavaScript. For example:
1document.getElementsByTagName("div")[0].innerHTML = "abc"; 2// innerHTML can be used to insert plain text content or HTML, this creates a list inside a <div> element
It can also be used to add entire new elements into your HTML without being so verbose as the createElement
examples above. Let's rework the `"Hello World" to see the difference:
1 document.querySelector("myFirstDiv").innerHTML += `<h1>Hello World</h1>`
Dramatic difference!!! We achieved the same result with one line of code that previously required 5 lines.
By using template literals (``) we can even break down the HTML elements onto separate rows, so it is easier to read them, and also we can use variable values, instead of hard-coded ones:
1 let greeting = "Hello World" 2 document.querySelector("myFirstDiv").innerHTML += ` 3 <div> 4 <h1> 5 ${greeting} 6 </h1> 7 </div> 8 `
☝️ Get into the habit of using this approach as it is much more concise and straightforward which also makes your code easier to read.
You can find another 2 properties on the internet:
nodeValue
andtextContent
, but they are not really universally used and are more limited in functionality.
The most straightforward method to remove an element from the DOM is the remove()
method.
For example, if we want to remove a <p>
element with id="firstP"
, we can do the following:
1// Removing all children from an element 2let element = document.querySelector("p#firstP"); 3element.remove();
To change any attribute of any object in the DOM, we need to use the .attribute
property just like this:
1// Changing attributes 2let element = document.querySelector("#someId"); 3element.someAttribute = "newValue";
For example, to change the value of a button element, you would need to code this:
1// Changing value attribute 2let btn = document.querySelector("#myButton"); 3btn.value = "newButton";
You can also change any CSS rule or property applied to the HTML elements by using the .style
attribute, like this:
1// Changing styles 2let element = document.querySelector("#myElementId"); 3element.style.color = "red"; 4element.style.backgroundColor = "blue";
☝️ Notice how css properties which consist of two words, like
background-color
, become one word in camel case in the DOM -backgroundColor
.
Many times as you dynamically change the content of your application, you would want to change the classes of some elements, because classes allow us to give our elements different styling and functionality.
Imagine that you are given a bootstrap button:
1<button id="myButton" class="btn btn-warning">Submit</button>
You would like to change its background color from yellow to red at some point of your application's runtime. You can do that by simply exchanging its bootstrap classes for background color:
1// Changing classes 2let btn = document.querySelector("#myButton"); 3btn.classList.remove("btn-warning"); 4btn.classList.add("btn-danger");
You can do the same thing with your own custom classes.
As you can see, the classList
property gives you access to the classes of a given element, and you can add or remove classes.
With this knowledge, now research and make sure to understand the method classList.toggle("newClass")
.
For more information about accessing the DOM, see: https://developer.mozilla.org/en-US/docs/Web/API/Document