Changing HTML Elements
In this tutorial, we’ll explore how to use JavaScript to dynamically change the content and attributes of HTML elements on a web page.
Changing Text Content
You can change the text content of an element using the .textContent
property.
// Find the element
const paragraph = document.querySelector("#my-paragraph");
// Change the text content
paragraph.textContent = "New text content!";
Changing HTML Content
You can also change the HTML content of an element using the .innerHTML
property.
// Find the element
const container = document.querySelector("#my-container");
// Change the HTML content
container.innerHTML = "<p>New <strong>HTML</strong> content!</p>";
Changing Attributes
Attributes can be changed using the .setAttribute()
method.
// Find the element
const image = document.querySelector("#my-image");
// Change the "src" attribute
image.setAttribute("src", "new-image.jpg");
image.src = "https://globaltechmastery.com"
step 2:
let myLink = document.querySelector("#myLink");
myLink.href = "https://globaltechmastery.com";
Changing Styles
Styles can be changed using the .style
property.
// Find the element
const button = document.querySelector("#my-button");
// Change the background color
button.style.backgroundColor = "blue";
//select all paragraphs and change font-size of the first and second paragraph in the list
let paragraph = document.querySelectorAll("p");
paragraph[1].style.fontSize = "2em";
paragraph[0].style.fontSize = "12em";
As a general rule of thumb, in order to get the style property name in javascript, you
should change the CSS property name to camelCase!:
color
becomescolor
background-color
becomesbackgroundColor
margin-top
becomesmarginTop
Adding, Removing and Toggling Classes
You can add and remove classes using the .classList
property.
// Find the element
const element = document.querySelector("#my-element");
// Add a class
element.classList.add("new-class");
// Remove a class
element.classList.remove("old-class");
// Toggles a class on/off for an element.
element.classList.toggle("class-name");
Conclusion
JavaScript provides powerful capabilities for dynamically changing HTML elements. Whether you’re modifying text, HTML content, attributes, styles, or classes, these techniques allow you to create dynamic and interactive web pages.