JavaScript

Selecting & Modifying Elements

Learn to manipulate the DOM! Master querySelector, getElementById, innerHTML, style, and classList.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Learn to manipulate the DOM! Master querySelector, getElementById, innerHTML, style, and classList. This hands-on tutorial focuses on practical implementation of selecting & modifying elements concepts.

Selecting & Modifying Elements

To change anything on a web page, you follow a simple 2-step process:

  1. Select the element you want to change.
  2. Modify it (change text, style, or attributes).

1. Selecting Elements 🎯

There are many ways to find elements, but these two are the most important.

A. querySelector (The Modern Way)

Selects the first element that matches a CSS selector.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

B. getElementById (The Fast Way)

Selects a specific element by its unique ID. It's slightly faster than querySelector but only works for IDs.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

C. Selecting Multiple Elements

Use querySelectorAll to get a list of all matching elements.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

2. Modifying Content 📝

Once you have an element, you can change what's inside it.

  • innerText: Changes the visible text.
  • innerHTML: Changes the HTML (allows you to add tags like <b>).
JAVASCRIPT PLAYGROUND
⏳ Loading editor…

3. Modifying Styles 🎨

You can change CSS directly using the .style property. Note that CSS properties use camelCase in JavaScript (e.g., background-color becomes backgroundColor).

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

4. Modifying Classes (Best Practice) 🏷️

Changing individual styles is messy. It's better to define classes in CSS and toggle them in JavaScript using classList.

  • add("class-name")
  • remove("class-name")
  • toggle("class-name")
JAVASCRIPT PLAYGROUND
⏳ Loading editor…

Practical Example: Dark Mode Toggle 🌙

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "DOM manipulation, querySelector, innerHTML, style, and classList"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 4

Which method selects ALL matching elements?

querySelector
querySelectorAll
getElementById
selectAll

Key Takeaways

querySelector finds the first match.
querySelectorAll finds all matches.
innerText for text, innerHTML for HTML.
style.property for quick fixes.
classList for clean styling (Best Practice).

What's Next?

Now that we can change elements, let's make them respond to user actions with Events!

Keep coding! 🚀