Skip to main content
Practice

Creating and Setting Attributes of HTML Elements

How can you add new elements to a web page or set the attributes of existing elements?

For this purpose, you can use the document.createElement() and Element.setAttribute() methods.

document.createElement("Button")

The document.createElement method creates a new HTML element.

By passing the element name as a string within the parentheses, like "Button" in the example below, the corresponding element is created.

Creating an HTML Element
const newButton = document.createElement('Button');
newButton.textContent = 'Click me!';

document.body.appendChild(newButton); // Adding the button to the web page

Element.setAttribute(name, value)

The Element.setAttribute method sets a new attribute or changes the value of an existing attribute for an element.

The target for setAttribute is an individual HTML element, not the document.

Pass the attribute name (Name) as the first argument, and the attribute value (Value) as the second argument to setAttribute.

Setting Attributes for an HTML Element
const newButton = document.createElement('Button');

newButton.setAttribute('id', 'specialButton'); // Setting the id attribute
newButton.setAttribute('class', 'bigButton'); // Setting 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.