How to Change a DOM Node Value: A Step-by-Step Guide
Changing the value of a DOM (Document Object Model) element is a common task in web development. Whether you want to update the text content of a paragraph, modify the value of an input field, or alter any other element within a webpage, there are straightforward ways to achieve this. In this article, we will explore how to change a DOM node value using JavaScript.
Method 1: Changing the innerText
Property
One way to modify the value of a DOM element is by updating its innerText
property. This property represents the visible text content of an element and allows you to change it dynamically.
To change the innerText
property, follow these steps:
- Identify the DOM element you want to modify. You can use the Selectors API to target the specific element. For example:
1 | const element = document.querySelector('#today .total'); |
In this example, we use the querySelector
function to find the element with id
“today” and class “total”.
- Update the
innerText
property of the element to the desired value. For instance, if you want to change it to ‘x’, use the following code:
1 | element.innerText = 'x'; |
After executing this code, the innerText
of the selected element will be updated to ‘x’.
Method 2: Changing the value
Property (For Input Fields)
If you want to change the value of an input field dynamically, you can modify its value
property. This method is useful when you want to update the content of text fields, checkboxes, radio buttons, or any other input element.
To change the value of an input field, follow these steps:
- Get a reference to the input element you want to modify using the Selectors API. For example:
1 | const inputField = document.querySelector('#myInput'); |
In this example, we use the querySelector
function to find the input element with id “myInput”.
- Assign the desired value to the
value
property of the input field. For instance, if you want to update the value to ‘New Value’, use the following code:
1 | inputField.value = 'New Value'; |
After executing this code, the value of the input field will be changed to ‘New Value’.
Conclusion
Changing the value of a DOM node is a fundamental skill in web development. By utilizing the innerText
or value
properties, you can easily modify the content of DOM elements and input fields dynamically.
Remember to use the appropriate property depending on the type of element you want to modify. Use innerText
for non-input elements and value
for input fields.
By following the step-by-step guide provided in this article, you’ll be able to change DOM node values seamlessly in your web projects.
Tags: DOM manipulation, JavaScript, Web development, Selectors API, Change value, InnerText, Value property