Select Element By Index In Jquery
In this topic, we will see how to select an element by index in jquery.
Select Element By Index:-
In any situation, we might want to
select an element by index. Jquery allows us to select an element by index. It
is very easy to perform this simple task using jquery. we will see different
types of examples to understand the topic easily.
Select Element By Index – Example 1(Less Than)
In the following example we
will see how to select all the <p> elements and change
the background
color that is less than the given index value.
$(‘p:lt(3)’).css(‘background-color’,’lightgreen’); This line tells jquery to select all the <p> element that is less than the index value. Here the index value is 3, so it will select all the <p> element that is less than the 3 and set the background color to lightgreen.
The following example is very
much similar to the above example. It will select all the <p> elements and change
the font style that is
greater then the given index value.
<!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>
$(document).ready(function(){
$('p:gt(3)').css('font-family','Comic Sans MS');
});
</script>
<body>
<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
<p>paragraph 4</p>
<p>paragraph 5</p>
<p>paragraph 6</p>
</body>
</html>
|
$(‘p:gt(3)’).css(‘font-family’,’Comic Sans MS’);This line tells jquery to select all the <p> element that is greater than the index value. Here the index value is 3, so it will select all the <p> element that is greater than the 3 and set the font to Comic Sans MS.
Select Element By Index – Example 3(Equal)
In the following HTML example,
we will see how to change the font style and background color of <p> elements which is
equal to the index value.
Post A Comment:
0 comments: