jquery - select an element if children not having a specific class -
i looking selector solution, not using .find() or other jquery functions.
i wander why if $('.parentclass:has(".childrenclass")'), returns elements if 1 of children has .childrenclass
but if $('.parentclass:not(".childrenclass")') returns elements if 1 of children has .childrenclass
is there way select element if of children have not specific class?
i wander why if $('.parentclass:has(".childrenclass")'), returns elements if 1 of children has .childrenclass if $('.parentclass:not(".childrenclass")') returns elements if 1 of children has .childrenclass
because :not(".childrenclass") not remotely opposite of :has(".childrenclass"). :not tests whether that element doesn't match selector. :has tests whether element's children match selector.
is there way select element if of children have not specific class?
yes, can combine :not , :has:
$(".parentclass:not(:has(.childrenclass))").css("background-color", "yellow"); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="parentclass"> should match, no children childrenclass </div> <div class="parentclass"> should match, <span>no children childrenclass</span> </div> <div class="parentclass"> shouldn't match, <span class="childrenclass">has children childrenclass</span> </div> <div class="parentclass"> shouldn't match, <span class="childrenclass">has children</span> <span class="childrenclass">with childrenclass</span> </div> i have admit really surprised me, :has has history of not playing nicely others. previously, thought you'd have use filter:
$(".parentclass").filter(function() { return $(this).find(".childrenclass").length == 0; }).css("background-color", "yellow"); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="parentclass"> should match, no children childrenclass </div> <div class="parentclass"> should match, <span>no children childrenclass</span> </div> <div class="parentclass"> shouldn't match, <span class="childrenclass">has children childrenclass</span> </div> <div class="parentclass"> shouldn't match, <span class="childrenclass">has children</span> <span class="childrenclass">with childrenclass</span> </div>
Comments
Post a Comment