Skip to main content

Selecting and Manipulating Elements

To change an element on the screen, JavaScript must first select it from the DOM tree. The globally available document object gives us the methods to do so.

1. Selecting Elements

<h1 id="title" class="heading">Welcome to JS</h1>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
// 1. Get by ID (Returns a single element)
const title = document.getElementById("title");

// 2. Query Selector (Extremely powerful. Uses CSS syntax like .class or #id)
const firstParagraph = document.querySelector(".text");
// querySelector ONLY returns the very first match it finds.

// 3. Query Selector All (Returns a NodeList of ALL matches)
const allParagraphs = document.querySelectorAll(".text");

2. Manipulating Elements

Once you have a reference to the element stored in a variable, you can modify its inner content or properties.

Changing Text

const title = document.getElementById("title");

// Modifies the raw text exactly as provided
title.innerText = "JavaScript is awesome!";

// Parses strings as HTML tags!
title.innerHTML = "JavaScript is <em>awesome!</em>";

Changing Styles

Every DOM element has a style property allowing direct inline CSS manipulation. Remember: In CSS, properties use kebab-case (background-color). In JavaScript, CSS properties become camelCase!

title.style.color = "blue";
title.style.backgroundColor = "lightgrey"; // Not background-color!
title.style.fontSize = "3rem";

Working with Classes

Manipulating style directly is clunky. It's much better to toggle CSS classes via the classList API.

// Assuming .highlight { background: yellow; } exists in your CSS
title.classList.add("highlight");
title.classList.remove("highlight");

// toggle() adds the class if missing, or removes it if present!
title.classList.toggle("highlight");