5.js-dom.md
Quiz
~/ hackweb.dev
...
~/
/tutorials
/en/js/js-dom/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
en/tutorials/js/5js-dom
# JavaScript and the DOM The DOM (Document Object Model) is how JavaScript talks to the page. You select elements, change them, and react to user actions. ## Selecting elements `querySelector` finds the first element that matches a CSS selector. ```js const heading = document.querySelector("h1"); const app = document.querySelector("#app"); console.log(app); ``` ## Changing content `textContent` sets the text of an element. ```js const app = document.querySelector("#app"); app.textContent = "hello from JavaScript"; ``` ## Listening to events `addEventListener` runs code when something happens — like a click. ```js const app = document.querySelector("#app"); app.addEventListener("click", () => { app.textContent = "you clicked me!"; }); ``` ## Creating elements Build new elements and attach them to the page. ```js const app = document.querySelector("#app"); const item = document.createElement("p"); item.textContent = "a brand new paragraph"; app.appendChild(item); ```
Submit suggestion
cancel