jQuery Traversing
0 1310
- In jQuery, traversing is used to select an HTML element or elements based on their relation to other HTML elements.
Related Topics:
jQuery wrap
jQuery unwrap
jQuery Traversing
- Traversing process contains a number of steps which starts by one selection and go ahead until you traversed the required element.
- There are few terms which used in traversing in jQuery:
1 Ancestor: ancestor represents the parent, grandparent, great-grandparent and other such type of elements which has parental relation to the selected element.
2 Descendant: descendant represents the child, grandchild, great-grandchild and other such type of elements those are child of the selected elements in relation.
3 Sibling: siblings are the elements which has the same parents as selected element.
We can explain it in more easy way with the help of example given below.
In the above tree,
1 The <div> element is the parent of <h1> and both <p> elements and it is an ancestor of all elements inside it.
2 The left <p> element is the parent of <img> element and also child of <div> element.
3 The <h1> element is the parent of both <span> elements and also child of <div> element.
4 The right <p> element is the parent of <b> element and also the child of <div> element.
5 The <img> element is the child of left <p> element.
6 Both <span> elements are the children of <h1> element.
7 <b> element is the child of right <p> element.
8 Both <p> elements and <h1> are the siblings.
9 Both <span> elements are the siblings.
- To traverse the DOM model of any webpage, jQuery provides a large variety of methods.
- In jQuery, we used tree-traversal methods to make traversing easy and convenient.
Example:
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:10px;
margin:10px;
font-size:20px;
}
p{
background:yellow;
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("span").parent().css("border","2px solid red");
$("p").children().css("border","2px solid green");
});
});
</script>
</head>
<body>
<h2> jQuery Traversing Example </h2>
<div>
<p><span> Hello Friends!!</span> <span> Welcome to CodingTag </span></p>
</div>
<button> Click Me! </button>
</body>
</html>
Output:
When you click the button,
Share:
Comments
Waiting for your comments