.next()
In this chapter you will learn:
- Syntax and Description for .next()
- How to select the next class
- How to get next tags
- Find the next sibling and apply style
- Find the next and change text
Syntax and Description
.next([selector])
gets the immediately following sibling of each element in the set of matched
elements, optionally filtered by a selector.
selector (optional)
is a string containing a selector
expression to match elements against.
The return value is the new jQuery object.
Next class
The following code selects the next elements who has certain class.
<html><!-- j a va 2s.c om-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button[disabled]").next(".selected").text("data");
});
</script>
<style>
.y { background:yellow; }
</style>
</head>
<body>
<body>
<div><button disabled="disabled">First</button> -
<span class="selected"></span></div>
</body>
</html>
Next tags
The following code selects the input element by name and then select tags next to it.
<html><!--from ja va 2s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[name='me']").next().text(" changed");
});
</script>
</head>
<body>
<div>
<input type="radio" name="me" value="A" />
<span>data</span>
</div>
<div>
<input type="radio" name="me" value="B" />
<span>data</span>
</div>
<div>
<input type="radio" name="me" value="C" />
<span>data</span>
</div>
</body>
</html>
Find the next sibling and apply style
Find the very next sibling of each paragraph that has a class "selected".
<html><!--from j av a 2 s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").next(".selected").css("background", "yellow");
});
</script>
</head>
<body>
<body>
<p>Hello</p>
<p class="selected">Hello Again</p>
</body>
</html>
Find the next and change text
The following code finds the next element after <p>
and sets text.
<html><!--from j av a 2 s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").next().text("java2s.com");
});
</script>
</head>
<body>
<body>
<p>bad or .</p><span>good</span>
</body>
</html>
Next chapter...
What you will learn in the next chapter: