Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting an element which has another element as direct child

Tags:

jquery

I need to select all divs which contain object as their direct child. :has just checks for descendants of any kind, so now I'm using:

$('div > object').parent().css('text-align', 'center');

is there a more direct way?

like image 789
Matteo Riva Avatar asked Feb 11 '10 09:02

Matteo Riva


2 Answers

You can simplify your code to:

$('div:has(> object)').css('text-align', 'center');
like image 135
fredrik Avatar answered Sep 18 '22 15:09

fredrik


Use the :has selector:

$("div:has(> object)").css("text-align", "center");

Here's an example I wrote up:

$(function() {
  $("div:has(> h3)").css("background", "yellow");
});
div { padding: 15px; border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div>
  <h2>outer</h2>
  <div>
    <h3>inner</h3>
  </div>
</div>
like image 38
cletus Avatar answered Sep 19 '22 15:09

cletus