janehouse janehouse - 5 months ago 22
CSS Question

How can I use JQ to pick out a parent whose child is hr.strong?

I am using Bootstrap and I have a bunch of containers with class .block. Some of those containers have an element hr.strong in them, some don't. Sample:

HTML

<div class="container-fluid block">
<div class="container">
<div class="row">
<hr class="strong">
</div>
<!-- end row -->
</div>
<!-- end container -->
</div>
<!-- end container-fluid -->



<div class="container-fluid block">
<div class="container">
<div class="row">
NO HR HERE
</div>
<!-- end row -->
</div>
<!-- end container -->
</div>
<!-- end container-fluid -->


I want to apply CSS (
padding:0
) only to .block that has hr.strong in it. How can I use JQ to pick out a parent whose child is hr.strong?

If there is a way to do with CSS only - that would be better.

Answer

Use selector.closest('.block'); This tells it to search up the dom for nearest element with given selector.

$("hr.strong").closest('.block').css("background","red");

$(function() {
  // Handler for .ready() called.
  $("hr.strong").closest('.block').css("background","red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

<div class="container-fluid block">
    <div class="container">
        <div class="row">
            <hr class="strong">
        </div>
        <!-- end row --> 
    </div>
    <!-- end container --> 
</div>
<!-- end container-fluid -->



<div class="container-fluid block">
    <div class="container">
        <div class="row">
            NO HR HERE
        </div>
        <!-- end row --> 
    </div>
    <!-- end container --> 
</div>