开发者

jQuery contains

开发者 https://www.devze.com 2022-12-12 03:32 出处:网络
Is there a way to get the deepest element matching a contains statement? Basicly if I have nested divs, I want the last element not the parent element:

Is there a way to get the deepest element matching a contains statement?

Basicly if I have nested divs, I want the last element not the parent element:

<div id="hayStack">
  <div id="needle">Needle</div>
</div>

$("div:contains('Needle')") is returning the hayStack div.

Th开发者_StackOverflowe only solution I have come up with so far is explicitly exlcuding parent divs by their id with .not


Adding :last will return the deepest/last div (the one immedietly encapsulating the content you are searching for

$("div:contains('Needle'):last")


$("div:contains('Needle')").filter(function() {
    return $(this).children().size() === 0;
});

Gets the list of elements containing 'Needle' then filters out those with any children.


I use this to find the deepest elements when the needle appears multiple times:

var needle = 'foo';
var $elms = $('#container').find(':contains('+needle+')').filter(function() {
        return $(this).find(':contains('+needle+')').length === 0;
    });

$elms.addClass('containsfoo');


There is another way that will allow you to find all deepest containers (not only the last one). Just find an element that contains no other jquery elements.

$('div:contains("Needle"):not(:has(*))').each(function() {
    console.log($(this).html());
});


I write code to find all deepest element for each leaf.

Main defer this code check deepest by parent, not by child, cause Needle deepest element can contain child too.

http://jsfiddle.net/ncppk0zw/20/

var found = $('div:contains("Needle")');

for (var i = 0; i < found.length; i++) {
    if (i > 1) {
        if (found[i].parentNode !== found[i-1]) {
            // Deepest. Next element is other leaf
            console.log(found[i-1]);
            continue;
        }
        if (i == found.length-1) {
            // Deepest. Last element in DOM tree
            console.log(found[i]);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消