Welcome to the magic world of JavaScript DOM manipulation! If web pages were a stage, JavaScript would be the mischievous director changing dialogues, costumes, and props on the fly!
1. Changing Text Content
Want to change what your webpage says? JavaScript has your back!
Example:
let heading = document.getElementById("title");
heading.innerText = "JavaScript is Awesome!";
Tip: innerText
changes the visible text, while innerHTML
can insert HTML elements.
Analogy: Like editing a script mid-performance!
2. Modifying Attributes
Attributes give extra information to HTML elements. JavaScript can tweak them as needed!
Example:
let image = document.getElementById("logo");
image.setAttribute("src", "new-logo.png");
Tip: You can use setAttribute()
or access properties directly (image.src = "new-logo.png";
).
Analogy: Like changing a character’s costume backstage!
3. Changing CSS Styles
JavaScript can also apply new styles dynamically!
Example:
let paragraph = document.querySelector("p");
paragraph.style.color = "blue";
paragraph.style.fontSize = "20px";
Tip: Use style
to modify individual properties or classList
to toggle predefined styles.
Analogy: Like giving your webpage a surprise makeover!
4. Adding and Removing Classes
Instead of modifying styles one by one, use class manipulation!
Example:
let box = document.getElementById("box");
box.classList.add("highlight");
box.classList.remove("hidden");
box.classList.toggle("active");
Tip: toggle()
adds the class if it’s missing and removes it if it’s present.
Analogy: Like switching between casual and fancy outfits with a snap!
Conclusion
JavaScript lets you dynamically change text, attributes, and styles, making your webpage interactive and engaging. So go ahead—start manipulating the DOM like a pro!
0 Comments