How can I manipulate the DOM using JavaScript?
Asked on Aug 13, 2024
Answer
To manipulate the DOM using JavaScript, you can use various methods provided by the Document Object Model (DOM) API. Here's a simple example demonstrating how to change the text content of an HTML element.
<!-- BEGIN COPY / PASTE -->
<div id="myElement">Original Text</div>
<script>
// Select the element by its ID
const element = document.getElementById('myElement');
// Change the text content of the element
element.textContent = 'Updated Text';
</script>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "document.getElementById" method is used to select an element by its ID.
- The "textContent" property is used to update the text inside the selected element.
- Ensure the script runs after the DOM is fully loaded, or place the script at the end of the body.
Recommended Links:
← Back to All Questions