lorem ...">

How to choose parent level first level using jQuery?

Consider the following markup:

<div id="0">
    <h1 id="1">
        <span id="2"><span id="3">lorem ipsum</span></span>
    </h1>
</div>

How can I find the first span # 3 parent that has a block level (i.e. has display: block) using jQuery? In this case, it will be h1#1.

+5
source share
4 answers
$("#3").parents().filter(function() {
    return $(this).css("display") === "block";
}).first()

http://jsfiddle.net/DFURw/

+10
source

Hmm. I think it will be


$('#3').parents().each(function(){

    if ($(this).css('display') == 'block') {
        console.log(this);
        //do your stuff if the element is block
        return false; // bail out
    }

});

+1
source

, :

var $el = $('#3');
while ($el.css('display') !== 'block' && ($el = $el.parent().length)){}

, $el , : block, , jQuery .

0

According to the W3C, a block level element may have a display of all content whose contents are treated as a table or block . So, without further adieu, here is my solution. I believe that you will find it much faster than the above solutions.

var elementBlockDisplays={"run-in":1,"block":1,"table-row-group":1,"table-column":1,"table-column-group":1,"table-header-group":1,"table-footer-group":1,"table-row":1,"table-cell":1,"table-caption":1,"inline-block:":1};

var getBlockParent = function(theElement){
    var cur=theElement.parentElement;
    while (cur&&!elementBlockDisplays[getComputedStyle(cur).display])
        cur=cur.parentElement;
    return cur;
};
0
source

All Articles