jQuery Selector parent > child

Introduction

The ("parent > child") selector selects all elements that are a direct child of the specified element.

("parent > child")
Parameter
Optional
Description
parent
Required.
parent element to be selected
child
Required.
direct child element (of the specified parent element) to be selected

Select all <span> elements that are a direct child of a <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 > span").css("background-color", "yellow");
});/*from  w  w w  . j a v a 2 s. c  o m*/
</script>
</head>
<body>

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

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

</body>
</html>



PreviousNext

Related