~/Home ~/Notes ~/Categories

Manipulating the DOM

26 September, 2020  ·   Javascript
  https://www.udemy.com/course/modern-javascript/

Properties and Methods of DOM

Lets look at some of the important properties and methods which we use regularly

innerText & textContent

innerText

1const h1 = document.querySelector("h1");
2h1.innerText; //My Web page
3const ul = document.querySelector("ul");
4ul.innerText; //"First2nd3rd" All the nested content is concatenated and output came as one object
5document.body.innerText; // we get all the text on the webpage, it doesnt matter it is nested or not
6//change the value
7h1.innerText = "Hello world"; // changes value to HW on html page
8ul.innerText = "asjgsakdj"; // all of the lis are gone and replaced with this text

textContent

1const h1 = document.querySelector("h1");
2h1.textContent; //My Web page

lets change our html to without any proper formatting and add a script tag

1<p id="main">
2  Lorem ipsum d sadkj saldkm olor sit amet consectetur, adipisicing elit.
3  <strong style="display : none">Minus omnis similikjdsof que itaque!</strong>
4  Quas, voluptatum quasi sapiente consectetur cupiditate vel omnis, dolore odit
5  sequi, doloribus deleniti est ipsum quo numquam eius.
6  <script>
7    console.log("Hello");
8  </script>
9</p>
1const p = document.querySelector("#main");
2p.innerText; // returns all the text inside main with formatting and no data from script and also it doesnt display the hidden text which is in strong tag
3p.textContent; //returns data without formatting and also data inside script tag and hidden data inside strong tag

innerHTML

innerHTML not only retrieves text inside the tags but also all the elements inside a particular tag

1const form = document.querySelector("form");
2form.innerHTML;
3/**
4 * "
5      <input type="text" name="" id="" placeholder="text">
6      <input type="password" name="" id="" placeholder="password">
7      <input type="submit">
8    "
9 */
1form.innerHTML = "sadjgd"; // entire form gets replaced by this text
2// we can also add html data using innerHTML
3form.innerHTML = " <b>i am a bold tag</b>"; // bolds out the data

innerText vs innerHTML

1const h1 = document.querySelector("h1");
2h1.innerText(); // My web page
3h1.innerHTML(); //My web page
4h1.innerHTML += "is cool"; //My web page is cool
5h1.innerHTML += "<b> !!! </b>"; //My web page is cool !!!
6h1.innerText += "<b> !!! </b>"; //My web page is cool !!! <b> !!! </b>

Important DOM properties

 1const inputs = document.querySelectorAll("input");
 2inputs[0].value; // value of an attribute, lets say attribute was text box, we get value inside text box
 3//lets assume inputs[1] is checkbox
 4inputs[1].value; // always gives output as one, whether it is checked or not
 5inputs[1].checked; //true or false
 6inputs[2].placeholder; //password
 7inputs[2].placeholder = "Enter your password";
 8
 9const a = document.querySelector("a");
10a.href; // http:// www.google.com
11
12const img = document.querySelector("img");
13img.src;

Getting & Setting attributes

We have getAttribute() & setAttribute() to access and set other properties of DOM

1<input type="range" min="50" max="100" step="10" />
1const range = document.querySelector('input[type="range"]');
2range.getAttribute("max"); //100
3range.getAttribute("min"); //50
4range.getAttribute("type"); //range
5range.getAttribute("lol"); //null
6range.setAttribute("min", "-100");
7range.setAttribute("type", "radio");

Finding parent /children/ siblings

Selecting an element based on current element

1<ul>
2  <li id="special">First</li>
3  <li>2nd</li>
4  <li id="special">3rd</li>
5</ul>
 1const firstLI = document.querySelector("li");
 2firstLI.parentElement; //entire ul currently this li is in.
 3/**
 4 *    <ul>
 5      <li id="special">First</li>
 6      <li>2nd</li>
 7      <li id="special">3rd</li>
 8    </ul>
 9 */
10firstLI.parentElement.parentElement; //entire body
11firstLI.parentElement.parentElement.parentElement; //entire html
12firstLI.parentElement.parentElement.parentElement.parentElement; //null
13
14const ul = document.querySelector("ul");
15ul.children; //HTMLCOllection(3) [li.special, li, li.special]
16ul.children[0].innerText; //First
17
18firstLI.nextElementSibling; //<li>2nd</li>
19const thirdLI = firstLI.nextElementSibling.nextElementSibling;
20thirdLI.previousElementSibling; //<li>2nd</li>

Changing multiple elements

We know how to select multiple elements, using querySelectorAll(). To manipulate them, iterate over the selected elements and change the property

1const allLis = document.querySelectorAll("li");
2
3for (let i = 0; i < allLis.length; i++) {
4  allLis[i].innerText = "We are champions";
5} // value of all lis is changed
6
7for (const li of allLis) {
8  li.innerHTML = "We are <b> Champions </b>";
9}

Altering Styles

Assigning each li a color..

1const allLis = document.querySelectorAll("li");
2const colors = ["red", "yellow", "blue", "green", "css", "pink"];
3allLis.forEach((li, i) => {
4  const color = colors[i];
5  li.style.color = color;
6});

getComputedStyle()

To get the styles we applied in a stylesheet (get the computed values of an element)

1const li = document.querySelector("li");
2const styles = getComputedStyle(li); //RT : CSSSTyleDeclaration. a massive object contains all CSS properties in K,V pairs. values are set to default unless we have mentioned them explicitly in stylesheet .

Manipulating classes

Apply style to multiple elements using css classes

1<ul id="todos">
2  <li class="todo">Eat breakfast<button>x</button></li>
3  <li class="todo">Feed the pet<button>x</button></li>
4  <li class="todo">Drink water <button>x</button></li>
5</ul>
 1.todo {
 2  font-size: 30px;
 3  color: olive;
 4}
 5
 6.done {
 7  color: gray;
 8  text-decoration: line-through;
 9  opacity: 50%;
10}
1const todos = document.querySelector("#todos .todo");
2todos.getAttribute("class");
3todos.setAttribute("class", "done");

classList

1//removes existing style on classes
2todos.classList.remove("done"); // using setAttribute we werent able to remove, now we can remove using classList
3//adds style on to classes
4todos.classList.add("done"); // add class
5//adds if we dont have and removes if we have it. toggles between two
6todos.classList.toggle("done");

Creating Elements

 1//create a h2 element and append it to dom
 2
 3//create
 4const newh2 = document.createElement("h2"); // creates an object on DOM
 5newh2; // <h2></h2>
 6//add text
 7newh2.innerText = "I love pineapples";
 8newh2; //<h2>I love pineapples</h2>
 9//lets add style too
10newh2.classList.add(".special");
11//append it to DOM
12//select a parent to attach
13const section = document.querySelector("section");
14section.appendChild(newh2); // this child is going to get appended at the end of the section  //<h2 class="special">I love pineapples</h2>
15
16//On webpage
17/* <section>
18  <ul>
19    <li>carrots</li>
20    <li class="special">potatoes</li>
21    <li>tomatoes</li>
22  </ul>
23  <h2 class="special">I love pineapples</h2>
24</section>; */
1//Example 2:
2const newLink = document.createElement("a");
3newLink.href = "https://www.youtube.com/watch?v=8Ljgy3pLmmo";
4newLink.innerText = "BTS - Dream Glow lyrics";
5const firstP = document.querySelector("p");
6firstP.appendChild(newLink);

Append, prepend and insertBefore

insertBefore

insert an element before a particular element.

 1parentEl.insertBefore(newEl, elBeforeWhichUwantToInsert);
 2//example.
 3//insert an li before the first li in an ul
 4const parentUl = document.querySelector("ul");
 5const newLi = document.createElement("li");
 6newLi.innerText = "I am a new list element";
 7const firstLI = document.querySelector("li.todo");
 8parentUl.insertBefore(newLi, firstLI);
 9// insert before last Li
10const lastLi = const firstLI = document.querySelectorAll("li.todo")[2];
11parentUl.insertBefore(newLi, lastLi);

insertAdjacentElement

 1const i = document.createElement("i");
 2i.innerText = "I am italics";
 3const firstP = document.querySelector("p");
 4firstP.insertAdjacentElement("beforebegin", i);
 5/**
 6 * i am italics
 7 * I am P tag
 8 */
 9
10firstP.insertAdjacentElement("afterbegin", i);
11/**
12 * i am italicsI am P tag
13 */
14
15firstP.insertAdjacentElement("afterend", i);
16/**
17 * I am P tag
18 * i am italics
19 */
20firstP.insertAdjacentElement("beforeend", i);
21
22/**
23 * I am P tagi am italics
24 */

append() & prepend()

 1firstP.append(i, newLi);
 2/**
 3 * I am P tagi am italics
 4 * i am a new li
 5 */
 6firstP.prepend(i, newLi);
 7/**
 8 * i am italics
 9 * i am a new li
10 * I am P tag
11 */

removeChild() and remove

Similar to appendChild() and append()

1const ul = document.querySelector("secion ul");
2const removeEl = ul.querySelector(".special");
3ul.removeChild(removeEl);
4
5//for remove u dont need a parent el to remove
6const h1 = document.querySelector("h1");
7h1.remove();
 javascript  dom  es6
Intro to DOM Manipulation↠ ↞Event Handling