【My Study Note】JavaScript Dom Manipulation
Contents
- 1. Codes
Codes

Contents
- 1. setAttribute()
- 2. appendChild()
- 3. querySelector()
- 4. getElementById()
- 5. getElementsByClassName()
setAttribute()
element.setAttribute("class", "democlass");
The setAttribute() method sets a new value to an attribute. In the case example above, it’s adding a class attribute to an element.
» More about this code
appendChild()
const h2 = document.createElement(h2);
h2.innerText = "Hi!";
h2.setAttribute("id", "greeting");
document.body.appendChild(h2);
The appendChild() method appends a node (element) as the last child of an element.
» More about this code
querySelector()
<div id ="nam">
<h1 class="greet">Hello</h1>
</div>
<script>
var x = document.getElementById("nam");
x.querySelector(".greet").innerHTML = "Hello World!";
</script>
The querySelector() method returns the first child element that matches a specified CSS selector(s) of an element.
» More about this code
getElementById()
const myElement = document.getElementById("demo");
myElement.style.color = "red";
The getElementById() method returns an element with a specified value.
» More about this code
getElementsByClassName()
const collection = document.getElementsByClassName("example");
The getElementsByClassName() method returns a collection of elements with a specified class name(s).
» More about this code