WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Select an Element by Name in jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: Use the Attribute Selector

You can use the CSS attribute selectors to select an HTML element by name using jQuery. The attribute selectors provide a very flexible and powerful mechanism for selecting elements.

Let's take a look at the following example to see how this works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Select Element by its Name Attribute</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Select and style elements on click of the button
    $("button").click(function(){
        // Select inputs whose name attribute value ends with '_name'
        $('input[name$="_name"]').css("border-color", "lime");
        
        // Select input which name attribute value is exactly 'email'
        $('input[name="email"]').css("border-color", "blue");
        
        // Select inputs whose name attribute value starts with 'zip'
        $('input[name^="zip"]').css("border-color", "red");
    });    
});
</script>
</head>
<body>
    <form>
        <p><label>First Name: <input type="text" name="first_name"></label><p>
        <p><label>Last Name: <input type="text" name="last_name"></label><p>        
        <p><label>Email Address: <input type="text" name="email"></label><p>
        <p><label>Zip Code: <input type="text" name="zip_code"></label><p>
        <button type="button">Style Inputs</button>
    </form>
</body>
</html>

Please check out the tutorial on CSS attribute selectors to learn more about it.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.