📜  jquery select by id - Html(1)

📅  最后修改于: 2023-12-03 15:32:09.704000             🧑  作者: Mango

jQuery Select By Id - HTML

jQuery is a popular JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. In this article, we will explore how to select HTML elements using their id attributes using jQuery.

Assuming we have the following HTML structure:

<!doctype html>
<html>
<head>
    <title>jQuery Select By Id - HTML</title>
</head>
<body>
    <div id="container">
        <h1>jQuery Select By Id - HTML</h1>
        <p>Selecting HTML elements by id using jQuery.</p>
    </div>
</body>
</html>
Selecting Elements by Id

To select the div element above by id, we can use the following jQuery code:

$(document).ready(function(){
    var containerElement = $('#container');
    console.log(containerElement);
});

This code creates a jQuery object for the div element with the id "container". The "#" character in the selector tells jQuery to find the element with the matching id. The resulting jQuery object is stored in the containerElement variable, which is then logged to the console.

We can also use the getElementById method in JavaScript and wrap it in a jQuery object, like so:

$(document).ready(function(){
    var containerElement = $(document.getElementById('container'));
    console.log(containerElement);
});

This will give us the same result as before.

Conclusion

Selecting HTML elements by id using jQuery is a simple process that can greatly simplify your JavaScript code. Using the "#" character in the selector, we can find the element with the matching id attribute and create a jQuery object to manipulate it.