--- id: create-modify-element # title: Create / modify DOM nodes # sidebar_label: DOM Manipulation title: DOM Manipulation slug: / --- import Admonition from "../components/Admonition" import Accordion from "../components/Accordion" ## Finding elements ### 1. `querySelector()` This method returns the **first element that matches the CSS selector**. If no match is found, it returns `null`. ```js var ele = document.querySelector(selector); // Ex. - body > div.container > div.box + div.box document.querySelector(".box"); // returns first div.box document.querySelector(".not-found"); // null ``` This method is also available on all DOM nodes. If you want to look within a specific element, this is very useful. ```js // Example - div.outer > div.inner outerEle.addEventListener((ev) => { var innerEle = ev.target.querySelector(".inner"); }); ``` [Read on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector) ### 2. `querySelectorAll()` This method returns **all the elements that match** the specified CSS selector. It returns a **static NodeList**, which contains the matching elements. If no match is found, it returns empty NodeList. :::note How to consume NodeList? NodeList is a iterable, so it can be iterated using `for..of` loop, or converted to a array using spread syntax like `[...nodelist]`. Here, the NodeList is static - meaning any changes in the DOM later does not affect the content of the existing collection. More about NodeList [here](https://developer.mozilla.org/en-US/docs/Web/API/NodeList). ::: ```js var paragraphs = document.querySelectorAll("p"); for (var p of paragraphs) { p.className = "note"; } ``` [Read on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll) ## Create / insert element ### 1. `createElement()` The `document.createElement` method creates a new HTML element, taking the tag name (`"div"`) as first argument. To set attributes and add the element to DOM, look at `.setAttribute` and `.appendChild` below. ```js var newEle = document.createElement("div") // creates
``` To add some text inside a element, you'll need to create a text node. `createTextNode` method takes a string as input and returns a new TextNode. ```js var newEle = document.createElement("div") var newText = document.createTextNode("Hello world") newEle.appendChild(newText) //
Hello world
```
[Read on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) ### 2. `setAttribute()` Every element has a `.setAttribute(name, value)` method, which can add/modify a attribute on the current element. `name` - the attribute name which should be added. Ex- `"type"`. `value` - value of the attribute. Ex- `"text"`. ```js var newInput = document.createElement("input") newInput.setAttribute("type", "text") // ``` [Read on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute)