Find a parent that contains a specific CSS property

I need to find the closest parent that contains the following css property:

background-image: url(*here goes a link to a valid image*);

You can probably find this by selecting all the elements, filtering them in the array and then using the first / last element of the array, but I would like to know if there is a faster way to select the closest parent that fulfills the requirement that I mentioned earlier, eg:

<parent1 style="background-image:url(http://google.com/images/photo.png);">
        <parent2 style="background-image:url('http://google.com/images/photo.png');">
                <mydiv></mydiv>
        </parent2>
</parent1>

I want parent 2 selected;

Keep in mind that I do not know background url .

+4
source share
3 answers

You can extend the jQuery selector to allow this. And with your specific rules.

Something like that:

$.extend($.expr[':'], {
  backgroundValid: function(a) {
    //change the url for what you want
    return $(a).css('background-image') === "url(http://stacksnippets.net/validurl)";
  }
});

var test = $('.foo').closest('div:backgroundValid');

console.log(test) //prints bar
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-image:url('validurl');">
  <div class="bar" style="background-image:url('validurl');">
    <div class="foo"></div>
  </div>
</div>
+4

, , jsfiddle

HTML

<div id="parent1" style="background-image:url(validurl);">
    <div id="parent2" style="background-image:url(validurl);">
        <div id="start"></div>
    </div>
</div>

Javascript

$(function() {
    var cssKey = "background-image";
    var element = $('#start');
    var found = false;
    while (!found) {
        element = element.parent();
        found = element.css(cssKey) == 'none' ? false : true;
        if (element.is($('html'))) break;
    }
    if (found) {
        console.log(element.attr('id'));
    } else {
        console.log('Not found');
    }
});
+1

Maybe this can help you,

  • select item
  • pick up all his parent
  • filter the parent element as you wish!

var firstParent, URL_TO_MATCH = "url(HELLO WORLD)";

$('#foo').parents().filter(function() {
  var isValid = $(this).css('background-image') == URL_TO_MATCH;
  

   if(!firstParent && isValid) {
     firstParent = $(this);
   }
  
   return isValid;
});
Run code
0
source

Source: https://habr.com/ru/post/1615413/


All Articles