SELECT ELEMENT BY ID
In this topic, we will see how to
select an element by id in jquery with few examples. Jquery is
very expert in allowing developers to select the page element by id,
so developers can work on them.
Note:- The ID selector
always includes the # (hash) symbol when referencing the ID in
the selector. Without that symbol, the selector won’t work correctly. The ID selector
returns only one ID that it matches.
When you use jQuery, you usually use a function named jquery( ) to get access to the jQuery library. In fact, there’s a shortcut, you can also call the function using $( ).
SELECTING ELEMENT BY ID-EXAMPLE 1
In this example, we
will see how to pick out a particular <p> element
by the id attribute value and set the background color to chocolate using jquery.
To access an element by ID “id”, you call the function $(#id), which returns the element with that ID.
$(‘#third’).toggleClass(‘addstyle’); This line tells jquery to select the page element by id of “third” and add CSS ‘addstyle‘ class to the selected element with the help of jQuery toggleClass( ) function.
So it will select <p id=” third”>This is paragraph</p> element because the id of this element is “third“ and set the CSS class to ‘add style‘. So the background of this particular element will be in chocolate color.
Output:-
Selecting element by id-Example 2
In this second example, we will see how to hide a particular ‘div’ using CSS. We will use a jquery selector to select the ‘id’ of the ‘div’ from the document to achieve the result. we’ll hide the ‘div’ when the user clicks a button with the jQuery CSS(); function.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function HideFunc(){
$('#HideMe').css('display','none');
};
</script>
</head>
<body>
<div id="HideMe">
<p>Click the Button to Hide</p>
</div>
<input type = "button" value="Click Me" onclick="HideFunc( )">
</body>
</html>
In the above example, we have selected the respective ‘div’ by using jQuery selector $(‘#HideMe’). And then using CSS(‘display’,’ none’); function we have set the CSS style to the selected ‘div’. Once the user clicks the button, the CSS properties will be applied to the selected ‘div’. so it will get hide.
Share this article with your friends
Post A Comment:
0 comments: