Select element with specific “id” in jQuery
In this tutorial, you will learn how to select a specific element in the document based on its id value, using jQuery.
Solution
To select a specific element in the document based on its id value using jQuery, use the #
selector followed by the id value, as shown in the following.
var myElement = $("#my-element-id");
Programs
1. In the following script, we select an element whose id="answer-1"
, and change its color.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Select the element with id="answer-1"
var myElement = $("#answer-1");
// Do something with the selected element
myElement.css("color", "red");
});
</script>
</head>
<body>
<h2>Hello User!</h2>
<p>This is a paragraph.</p>
<p id="answer-1">This is another paragraph.</p>
</body>
</html>