In previous pages we learned a little about the DOM
. It is possible to manipulate the DOM
via the console
.
For example, if we type document
into it, console
will return all the elements within the document.
From here, we can assign variables
and access each element:
let lis = document.getElementsByTagName("li")
let uls = document.querySelector("ul");
let dropdownMenu = document.querySelector(".dropdown-submenu");
let dropdown = document.querySelector("#dropdown");
let heading = document.querySelector("h1");
returns all elements with the tag li
once called.
A more flexible way to do this is to use querySelector
returns all elements with the tag ul
once called.
returns all elements in the class dropdown-submenu
once called.
returns all elements with the Id dropdown
once called.
From here, we can use textSelector
to call the contents:
<h1>jQuery:</h1>
heading.textContent;
jQuery:
We can also look for child
or parent
elements:
let uls = document.querySelector("#dom-manipulation");
uls.children
We can also look for sibling
elements:
let uls = document.querySelector("#dom-manipulation");
uls.nextElementSibling
We can also create elements:
let li = document.createElement("li");
Adding a class name:
li.classList.add("last");
Adding a style:
li.style.backgroundColor = "blue";
li.style.color = "#c13e70";
Adding some text content:
li.textContent = "I was created!"
Now get the parent element
let uls = document.getElementsByTagName("ul");
Now get the parent element by Index number
let ul = uls[10];
Now append our <li>
to its parent element, <ul>
ul.appendChild(li)
We can also change their place. Using the above, and adding:
let li1 = ul.getElementsByTagName("li");
let firstLi = li1[0];
let lastLi = li1[8];
firstLi.classList.remove("first");
uls[10].insertBefore(lastLi, firstLi);
However, this soon becomes cumbersome: If we want to change these elements, or their conntents, we need to do so using a loop.
It would be much easier to do so if we had an API. And that is where jQuery
comes in:
jQuery
allows us to write "pseudo code" like:
ul.find("li").removeClass("first").addClass("new").css("background-color: "pink")...