Get an element by name with JavaScript/jQuery
This post will discuss how to get elements by name using JavaScript and jQuery.
1. Using jQuery
You can use the Attribute Equals Selector ([name='value']) to select elements with the given name in jQuery. Note, this might return more than one element since one can apply the same name to multiple elements within the document.
jQuery
|
1 2 3 4 5 6 |
$(document).ready(function() { var languages = $("[name='language']"); for (var lang of languages) { console.log(lang.value); } }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<p>Select your preferred language:</p> <div> <input type="radio" id="english" name="language" value="english" checked> <label for="english">English</label> <input type="radio" id="hindi" name="language" value="hindi"> <label for="hindi">Hindi</label> <input type="radio" id="spanish" name="language" value="spanish"> <label for="spanish">Spanish</label> </div> |
2. Using JavaScript
In pure JavaScript, you can use the native getElementsByName() method, which returns the NodeList of all elements having the given name.
JS
|
1 2 3 4 |
var languages = document.getElementsByName("language"); for (var lang of languages) { console.log(lang.value); } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<p>Select your preferred language:</p> <div> <input type="radio" id="english" name="language" value="english" checked> <label for="english">English</label> <input type="radio" id="hindi" name="language" value="hindi"> <label for="hindi">Hindi</label> <input type="radio" id="spanish" name="language" value="spanish"> <label for="spanish">Spanish</label> </div> |
Alternatively, you can use the querySelectorAll() method to get all elements within the document having the given name.
JS
|
1 2 3 4 |
var languages = document.querySelectorAll("[name='language']"); for (var lang of languages) { console.log(lang.value); } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<p>Select your preferred language:</p> <div> <input type="radio" id="english" name="language" value="english" checked> <label for="english">English</label> <input type="radio" id="hindi" name="language" value="hindi"> <label for="hindi">Hindi</label> <input type="radio" id="spanish" name="language" value="spanish"> <label for="spanish">Spanish</label> </div> |
That’s all about getting an element by name in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)