The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. Using JavaScript, we can access and manipulate the DOM to create dynamic web pages.
To access the DOM, we use the document
object in JavaScript. The document
object represents the entire HTML document, and we can use its properties and methods to manipulate the document.
Changing HTML Elements
We can use JavaScript to change HTML elements on the page. For example, we can change the text inside an HTML element, or we can change the value of an input field. This is done by manipulating the properties of the HTML elements.
Changing Text
To change the text inside an HTML element, we can use the innerHTML
property. This property sets or returns the HTML content (inner HTML) of an element. Here’s an example:
// Get the element with ID "myElement"
var element = document.getElementById("myElement");
// Change the text inside the element
element.innerHTML = "Hello, world!";
Changing Input Values
To change the value of an input field, we can use the value
property. This property sets or returns the value of the value attribute of an input element. Here’s an example:
// Get the input element with ID "myInput"
var input = document.getElementById("myInput");
// Change the value of the input field
input.value = "New value";
Adding and Removing HTML Elements
We can also use JavaScript to add and remove HTML elements on the page. For example, we can add a new paragraph to the page, or we can remove an existing button. This is done by creating or removing elements and then adding or removing them to or from the DOM.
Adding Elements
To add a new HTML element to the page, we can use the createElement()
method to create the element, the innerHTML
property to add content to the element, and the appendChild()
method to add the element to the page. Here’s an example:
// Create a new paragraph element
var newParagraph = document.createElement("p");
// Add some text to the paragraph
newParagraph.innerHTML = "This is a new paragraph!";
// Add the paragraph to the page
document.body.appendChild(newParagraph);
Removing Elements
To remove an existing HTML element from the page, we can use the removeChild()
method. This method removes a specified child node of the specified element. Here’s an example:
// Get the button element with ID "myButton"
var button = document.getElementById("myButton");
// Remove the button from the page
button.parentNode.removeChild(button);
Conclusion
JavaScript provides powerful tools for interacting with the Document Object Model (DOM) and creating dynamic web pages. By accessing and manipulating HTML elements on the page, we can create rich and engaging user experiences. With these techniques, we can create pages that respond to user actions, update dynamically, and provide feedback to the user.