Lecture
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
Lessons in this chapter ยท How does JavaScript work in the browser?
- 1. How Do Browsers Work?
- 2. DOM (Document Object Model)
- 3. Browser Window Object
- 4. Window - window.screen
- 5. Window - window.location
- 6. Methods to Select HTML Elements - 1
- 7. How to Select HTML Elements - 2
- 8. Creating and Setting Attributes of HTML Elements
- 9. Events
- 10. Advanced Event Handling
- 11. Multiple-choice quiz
- 12. JSON(JavaScript Object Notation)
- 13. Promise
- 14. Async/Await Handling Asynchronous Processes
- 15. Cookies
- 16. Multiple-choice quiz
- 17. JavaScript Summary
Quiz
0 / 1
The document.createElement('Button') method can create a new HTML button element.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help