How to select first block level parent with jQuery?

元气小坏坏 提交于 2019-12-12 10:50:07

问题


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 parent of span#3 that is of block level (i.e. has display: block) using jQuery? In this case that would be h1#1.


回答1:


$("#3").parents().filter(function() {
    return $(this).css("display") === "block";
}).first()

http://jsfiddle.net/DFURw/




回答2:


Hmm. . . I think that would 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
    }

});




回答3:


This solution is the shortest and will not search any more elements than necessary:

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

When finished, $el will be either a parent element that is display: block, or if there are none it will be a jQuery element with no items.




回答4:


According to W3C, a block level element can have a display of anything whose contents are processed like a table or a block. So, without further adieu, here is my solution. I believe you will find it to be 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;
};


来源:https://stackoverflow.com/questions/8576564/how-to-select-first-block-level-parent-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!