C4: Session 12
Creating HTML Content with JavaScript
Review
DOM Query Methods
JavaScript DOM methods are used to interact with the HTML DOM and manipulate its content. Some of the most commonly used methods include:
-
document.getElementById -
document.getElementsByClassName -
document.getElementsByTagName -
document.querySelector -
document.querySelectorAll
Concept: The HTML DOM
Creating Elements
The createElement method is a built-in method in the DOM that allows you to create a new HTML element. You can then modify the properties and attributes of the element and add it to the DOM.
// create a new paragraph element
const newParagraph = document.createElement('p');
// add some text to the paragraph element
newParagraph.textContent = 'Hello, world!';
// add the new paragraph to the body of the document
document.body.appendChild(newParagraph);
Concept: The HTML DOM
Creating Elements
Another example:
// create a new link element
const newLink = document.createElement('a');
// set the link text and URL
newLink.textContent = 'Google';
newLink.setAttribute('href', 'https://www.google.com');
// add the new link to the body of the document
document.body.appendChild(newLink);
Concept Practice: DOM Elements
Next Session
Browser Events
C4-Session12
By Sharynne Azhar
C4-Session12
- 10