Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select outermost div of a nest of selected divs

I am trying to use jQuery to select a div, but ignore all divs selected that are children of a selected div. No divs have any other way to identify them other than an HREF that I am matching. For example:

outerdiv = $('a[href^="http://bizmate."]').closest('div');
outerdiv.prepend("This was selected")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Won't be selected
  <div>
    Powered by <a href="http://bizmate.in">Bizmate</a>
    <div>
      Powered by <a href="http://bizmate.in">Bizmate</a>
      <div>
        Powered by <a href="http://bizmate.in">Bizmate</a>
      </div>
    </div>
  </div>
</div>

<div>
  <div>
    Powered by <a href="http://bizmate.in">Bizmate</a>
  </div>
</div>

This code selects all the divs, including the child. How can I limit it to only select the outermost div that satisfies the condition while ignoring the child divs that also satisfy the given condition?

Edit:

Currently, the example would give:

Won't be selected
This was selectedPowered by Bizmate
This was selectedPowered by Bizmate
This was selectedPowered by Bizmate
This was selectedPowered by Bizmate

I want the result to be:

Won't be selected
This was selectedPowered by Bizmate
Powered by Bizmate
Powered by Bizmate
This was selectedPowered by Bizmate

like image 807
Anthony Barrera Avatar asked Nov 16 '15 04:11

Anthony Barrera


1 Answers

This will select any top level parent, independent of the amount of clusters or their exact structure by filtering out the children based on the amount of links found down the tree :

var link = 'a[href^="http://bizmate."]',

outerdiv = $(link).filter(function() {

    var total = $(this).parents('div:last').find(link).length;

    if (total > 1) {
      var parent = $(this).closest('div').find(link).length;
      if (parent == total) return $(this);
    }
    else return $(this);

}).closest('div');

outerdiv.prepend("This was selected");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Won't be selected
  <div>
    Powered by <a href="http://bizmate.in">Bizmate</a>
    <div>
      Powered by <a href="http://bizmate.in">Bizmate</a>
      <div>
        Powered by <a href="http://bizmate.in">Bizmate</a>
      </div>
    </div>
  </div>
</div>

<div>
  <div>
    Powered by <a href="http://bizmate.in">Bizmate</a>
  </div>
</div>
like image 125
Shikkediel Avatar answered Oct 12 '22 22:10

Shikkediel