Skip to content
the poor coder

get value of element html js

Poor Man
Published
Reading time
1 min read

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:

Text
 <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:

Text
 <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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC