get value of element html js

How to Get the Value of an HTML Element using JavaScript

If you want to get the value of an HTML element using JavaScript, you can use the getElementById() method. This method looks for an HTML element with a specified ID and returns the element as an object.

Here's an example:

 <div id="myDiv">Hello World!</div>

<script>
  var myDiv = document.getElementById("myDiv");
  console.log(myDiv.innerHTML); // Output: "Hello World!"
</script>

In the above example, we have an HTML div element with an ID of "myDiv". We use the getElementById() method to get this element and assign it to the variable myDiv. We then use the innerHTML property to get the content of the div element, which is "Hello World!". We log this value to the console using the console.log() method.

Another way to get the value of an HTML element using JavaScript is by using the querySelector() method. This method allows you to select elements using CSS selectors.

Here's an example:

 <div class="myClass">Hello World!</div>

<script>
  var myDiv = document.querySelector(".myClass");
  console.log(myDiv.innerHTML); // Output: "Hello World!"
</script>

In the above example, we have an HTML div element with a class of "myClass". We use the querySelector() method to select this element using the CSS selector ".myClass". We then use the innerHTML property to get the content of the div element, which is "Hello World!". We log this value to the console using the console.log() method.

These are just two of the many ways you can get the value of an HTML element using JavaScript. It's important to choose the method that works best for your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe