More often, JS developers need to extract values from different HTML elements. It could be getting input values from a form, getting text from a paragraph, or accessing attribute values – understanding how to get values from elements is very essential.
Table of Contents
Here in this post “Mastering Getvalue in JavaScript“, I am going to share different JS methods to get values from elements. I will showcase all of my code examples with simple explanations. You can practice them independently. Also discuss industry-standard best practices so that you can apply the examples based on different scenarios.
So, this article is going to be very interesting. Keep reading till the end and know how to use getValue in JavaScript.
Understanding getValue in JavaScript
Using JS, you can access DOM elements, properties, and methods. Here are some common use cases where you need to extract values from elements:
- Input Fields: Capturing user inputs. Such as textField.
- Text Content: Extracting text from HTML elements. Such as DIV, paragraph.
- Attributes: Accessing attribute values of elements. Such as image path from image element.
JavaScript read input value
To get the value of an input field, you can simply use the .value property. Here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Getvalue in JavaScript Example</title>
</head>
<body>
<input type="text" id="username" placeholder="Enter your username">
<button onclick="getUsername()">Submit</button>
<script>
function getUsername() {
let username = document.getElementById('username').value;
console.log(username);
}
</script>
</body>
</html>
Output
Code Explanation
- HTML Input Element: <input type=”text” id=”username”> creates a text input field.
- JavaScript Function: getUsername() gets the value of the input field using document.getElementById(‘username’).value. Then print into the browser console.
Getting Text Content from Elements
If you want to get values from paragraphs, headings, or divs, you can use the .textContent property. Look at the below example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Text Content Example</title>
</head>
<body>
<p id="pulseMsg">Hi, Is this JS post Helpful?</p>
<button onclick="getMessage()">Show Message</button>
<script>
function getMessage() {
let message = document.getElementById('pulseMsg').textContent;
console.log(message);
}
</script>
</body>
</html>
Output
Code Explanation
The JS custom function getMessage() gets the text content of the paragraph using document.getElementById(‘message’).textContent.
You may be confused with .textContent and .innerText JS methods. Here we explained every use case with the example of changing button text using JS and all available methods, including .textContent and .innerText JS methods.
Getting Attribute Values
In JavaScript, attributes always provide additional information about elements. And some times we need to extract those values in runtime. To get attribute values, you can use the .getAttribute method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Get Attribute Value Example</title>
<style>
img{
width:300px;
height:300px;
}
</style>
</head>
<body>
<img id="myImage" src="https://upload.wikimedia.org/wikipedia/commons/d/d1/Brendan_Eich_Mozilla_Foundation_official_photo.jpg" alt="JS Inventor">
<br>
<button onclick="getImageSrc()">Get Image Src</button>
<script>
function getImageSrc() {
let imageSrc = document.getElementById('myImage').getAttribute('src');
console.log(imageSrc);
}
</script>
</body>
</html>
Output
You can also Get Image Path from Element using different JS selectors. So try those also.
Using querySelector and querySelectorAll
In some of the cases, you may not be able to use getElementById to select an HTML component. In those cases, querySelector and querySelectorAll can provide flexible ways to get elements and their values. Here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Query Selector Example</title>
</head>
<body>
<div class="user" data-id="1">User 1</div>
<div class="user" data-id="2">User 2</div>
<button onclick="getUserData()">Get User Data</button>
<script>
function getUserData() {
let users = document.querySelectorAll('.user');
users.forEach(user => {
let userId = user.getAttribute('data-id');
let userName = user.textContent;
console.log(`ID: ${userId}, Name: ${userName}`);
});
}
</script>
</body>
</html>
Output
Code Explanation
- HTML Div Elements: <div class=”user” data-id=”1″>User 1</div> creates div elements with a class and a data attribute.
- JavaScript Function: getUserData() uses document.querySelectorAll(‘.user’) to select all elements with the class “user” and retrieves their data-id attribute and text content.
More Examples
Example 1: Getting Value from a Select Dropdown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Select Value Example</title>
</head>
<body>
<select id="colorSelect">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
<button onclick="getSelectedColor()">Get Selected Color</button>
<script>
function getSelectedColor() {
let selectedColor = document.getElementById('colorSelect').value;
console.log(selectedColor);
}
</script>
</body>
</html>
Output
Example 2: Getting Checkbox Values
Demonstrating how to read checked and unchecked checkboxes in JS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Checkbox Value Example</title>
</head>
<body>
<input type="checkbox" id="subscribe" name="subscribe" value="newsletter">
<label for="subscribe">Subscribe to newsletter</label>
<button onclick="getCheckboxValue()">Get Checkbox Value</button>
<script>
function getCheckboxValue() {
let isChecked = document.getElementById('subscribe').checked;
console.log(isChecked ? "Subscribed" : "Not Subscribed");
}
</script>
</body>
</html>
Output
Summary Table
Element Type | Method | Example Code |
Input Fields | .value | let value = element.value; |
Text Content | .textContent | let text = element.textContent; |
Attribute Values | .getAttribute(attrName) | let attr = element.getAttribute(‘src’); |
Query Selector Single | querySelector | let elem = document.querySelector(‘.class’); |
Query Selector All | querySelectorAll | let elems = document.querySelectorAll(‘.class’); |
Best Practices
- Consistency: Use common methods for getting values to maintain code readability. Use common selectors also. Use .value always whenever applicable.
- Validation: Always validate and sanitize user input to avoid security vulnerabilities.
- Modularity: Create reusable functions for getting values to keep your code modular and maintainable. Try to build a JS utility class.
Conclusion
So far, I have discussed how to get values in JavaScript with different examples. Whether you are working with input fields, text content, or attributes, the methods I have discussed in this post will help you to get values efficiently. By using the provided examples and best practices, you are now able to handle various cases with different HTML elements involving getValue in JavaScript. Happy coding!
๐๏ธโโ๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐ฅ Asp.net C# Developer
๐ Solution Architect
๐จโโ๏ธ Database Administrator
๐ข Speaker
๐ MCTS since 2009
Leave a Reply