Flat Preloader Icon

getelement by name

The getElementByName() method in JavaScript is used to retrieve a reference to the first element with a specified value for the name attribute within the current document or within a specified element. It is similar to getElementById(), but instead of searching for elements by their id, it searches for elements by their name attribute.

Syntax:

				
					document.getElementsByName(name)

				
			

Parameters:

  • name (required):
    • A string representing the value of the name attribute of the elements to be retrieved.

Return Value:

  • An HTMLCollection object representing a live collection of elements with the specified name attribute value. If no elements are found, an empty collection is returned.
				
					<!DOCTYPE html>
<html>
<head>
    <title>getElementByName Example</title>
</head>
<body>
    <form>
        <input type="text" name="username" 
        value="John">
        <input type="email" name="email" 
        value="john@example.com">
        <input type="checkbox" name="subscribe" 
        checked>
        <input type="submit" value="Submit">
    </form>

    <script>
// Get the input element with the
name "username"
        let usernameInput =
        document.getElementsByName("username")[0];
        console.log(usernameInput.value);
        // Output: John

        // Get all checkbox elements with
        the name "subscribe"
        let subscribeCheckboxes =
        document.getElementsByName("subscribe");
        console.log(subscribeCheckboxes.length);
        // Output: 1
        console.log(subscribeCheckboxes[0].checked);
        // Output: true
    </script>
</body>
</html>

				
			

Note:

  • The name attribute should be unique within the document or within a specific scope to ensure accurate retrieval of elements.
  • If multiple elements have the same name, getElementsByName() returns a collection of all matching elements.
  • Since getElementsByName() returns a live HTMLCollection, changes to the DOM are reflected dynamically in the collection.

Compatibility:

  • getElementsByName() is supported in all major browsers including Chrome, Firefox, Safari, Edge, and Internet Explorer.