Creating HTML Elements and Setting Attributes
How can you add new elements to a web page or set attributes for existing elements?
To accomplish this, we use methods like document.createElement()
and Element.setAttribute()
.
document.createElement("button")
The document.createElement
method is used to create new HTML elements.
For example, by passing "button"
as a string within the parentheses, a corresponding HTML element is created.
Creating an HTML Element
const newButton = document.createElement('button');
newButton.textContent = 'Click me!';
document.body.appendChild(newButton); // Add the button to the web page
Element.setAttribute(name, value)
The Element.setAttribute
method is used to set a new attribute or change the value of an existing attribute for an HTML element.
The target of setAttribute is not the document, but a single HTML element.
The first argument to setAttribute
is the attribute's name, and the second argument is the attribute's value.
Setting Attributes on an HTML Element
const newButton = document.createElement('button');
newButton.setAttribute('id', 'specialButton'); // Set the id attribute
newButton.setAttribute('class', 'bigButton'); // Set the class attribute
// The button now has id="specialButton" and class="bigButton" attributes
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.