Syntax error jQuery next() method

jQuery next() method



The next() selector in jQuery is used to return the next sibling element of the selected element.

Syntax

The syntax is as follows −

$(selector).next(filter)

Above, the parameter filter is a selector expression to narrow down the next sibling search

Example

Let us now see an example to implement the jQuery next() selector −

<!DOCTYPE html>
<html>
<head>
<style>
   .demo * {
      display: block;
      border: 3px dashed red;
      padding: 3px;
      margin: 25px;
   }
   .one {
      border: 2px solid yellow;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("span.test").next().addClass("one");
   });
</script>
</head>
<body>
<h1>Heading One</h1>
<div class="demo" style="width:600px;">This is our demo text in div.
<p>child
<span>grandchild</span>
<span class="test">grandchild</span>
<span>grandchild</span>
</p>
<p>child
<span>grandchild</span>
</p>
</div>
</body>
</html>

Output

This will produce the following output −

Example

Let us now see another example −

<!DOCTYPE html>
<html>
<head>
<style>
   .demo * {
      display: block;
      border: 3px solid yellow;
      padding: 3px;
      margin: 25px;
   }
   .one {
      border: 2px solid blue;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("span.test").next().addClass("one");
   });
</script>
</head>
<body>
<h1>Heading One</h1>
<div class="demo" style="width:600px;">This is our demo text in div.
<p>child
<span>grandchild</span>
<span>grandchild</span>
<span>grandchild</span>
<span class="test">grandchild</span>
<span>grandchild</span>
<span>grandchild</span>
</p>
</div>
</body>
</html>

Output

This will produce the following output −

Updated on: 2019-11-11T12:50:49+05:30

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements