jQuery Selector element + next

Introduction

The ("element + next") selector selects the "next" element of the specified "element".

The "next" element must be right after the specified "element".

If you have two <p> elements right after a <div> element.

<div><p>p1</p><p>p2</p></div>

$("div + p") will only select the first <p> element.

Both of the specified elements must share the same parent.

("element + next")
Parameter Optional Description
element Required.Any valid jQuery selector
next Required.the element that should be the next element of the element parameter

Select the <p> element that are next to each <div> element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("div + p").css("background-color", "yellow");
});//from  w ww  .  j a v  a2 s .c  om
</script>
</head>
<body>

<div style="border:1px solid black;padding:10px;">This is a div element.</div>
<p>This p element is next to a div element.</p>
<p>This is another p element.</p>

<div style="border:1px solid black;padding:10px;">
  <p>This is a p element inside a div element.</p>
</div>

</body>
</html>



PreviousNext

Related