Traversing in jQuery is basically used to search or select HTML elements or attributes of a web page. During the traversal, we are using filtering methods to manipulate the DOM. Some filtering methods describe as below...
first(): This method searches the first element of selected HTML tag.
Example:
$("div span").first().text("Select very first <span> of a <div> from a web page and change their text").css("background-color", "yellow");
In this example, we selected very first <span> of a <div> from a web page and changed their text & background color .
last(): This method searches a last element of selected HTML tag in a web page
Example:
$("div span").last().text("Select most last <span> of a <div> from a web page and change their text").css("background-color", "orange");
In this example, we selected most last <span> of a <div> from a web page and changed their text & background color .
Eq(): This method gives an element with a specified index of the selected HTML tag.
Example:
$("span").eq(3).css("font-weight", "bold");
In this example, we selected fourth <span>(i.e. <span> with third index) from a web page and changed their font-wait.
filter(): This method provides facility to specify the criteria with the selector and gives result according to matched conditions.
Example:
$("p,span").filter(".test").css("background-color", "red");
In this example, we selected all <p> and <span> which have class "test" from a web page and changed their background-color.
not(): This method work unlike filter() and gives a result which does not match conditions
Example:
$("p,span").not(".test").css("background-color", "gray");
In this example, we selected all <p> and <span> which haven't class "test" from a web page and changed their background-color.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Using first()
$("div span").first().text("Select very first <span> of a <div> from a web page and change their text").css("background-color", "yellow");
//Using last()
//$("div span").last().text("Select most last <span> of a <div> from a web page and change their text").css("background-color", "orange");
//Using eq()
//$("span").eq(3).css("font-weight", "bold");
//Using filter()
//$("p,span").filter(".test").css("background-color", "red");
//Using not()
//$("p,span").not(".test").css("background-color", "gray");
});
</script>
</head>
<body>
<h3>Traverse using first() methods</h3>
<p>First paragraph in this page.</p>
<div style="border: 2px solid green;">
<span>This is the First span.</span>
<br>
<span class="test">This is the Second span.</span>
</div><br>
<div style="border: 2px solid gray;">
<span class="test">This is the First span in Second div.</span>
</br>
<span>This is the Second span in Second div.</span>
</div>
<p class="test">Last paragraph in this page.</p>
</body>
</html>
0 Comment(s)