简体   繁体   English

当父有兄弟姐妹时,如何获取元素的父节点?

[英]How to get the parent node of an element when the parent has siblings?

Please take a look at the snippet below: 请看下面的代码:

<div>
    <div></div>
    <div><!-- my target node -->
        <div><!-- not my target node -->
            <img /><!-- my source node -->
        </div>
    </div>
</div>

As you can see the img -elment has two enclosing div s. 正如你所看到的, img -elment有两个封闭的div I want the first of those two enclosing div s to be considered the "real" parent (the one I need to find) of the img -elment because it has a brother div before so the search ends and the brother div and the outer enclosing div are ignored. 我希望这两个封闭div第一个被认为是img -elment的“真正的”父级(我需要找到的),因为它之前有一个兄弟div ,所以搜索结束,兄弟div和外部封闭div被忽略了。

In the case there are no siblings at all, the outer div has to be yielded; 在没有兄弟姐妹的情况下,外部div必须得到; in the case the element is not enclosed, the element itself has to be yielded. 在元素未被封闭的情况下,元素本身必须被生成。

I just would like to know how to target the element as I explained via JavaScript. 我只是想知道如何通过JavaScript解释该元素。

So it sounds like you want the first ancestor that has siblings elements. 所以听起来你想要第一个拥有兄弟姐妹元素的祖先。 If so, you can do it like this: 如果是这样,你可以这样做:

var parent = img.parentNode;

while (parent && !parent.previousElementSibling && !parent.nextElementSibling) {
    parent = parent.parentNode;
}

Or perhaps more appropriately written as a do-while loop: 或者更恰当地写为do-while循环:

do {
    var parent = img.parentNode;
} while (parent && !parent.previousElementSibling && !parent.nextElementSibling);

So the loop will end when it finds one with at least one sibling element, or when it runs out of ancestors. 因此,循环将在找到具有至少一个兄弟元素的循环时,或者当它用完祖先时结束。

If you know if the sibling comes before or after the parent, you can just test for one or the other. 如果您知道兄弟姐妹是在父母之前还是之后,您可以只测试一个或另一个。


Also note that you'll need a shim for the ***ElementSibling properties if you're supporting legacy browsers. 另请注意,如果您支持旧版浏览器,则需要使用***ElementSibling属性的垫片。

You can make a function that will do this: 你可以创建一个可以执行此操作的函数:

function prevElement(el) {
    while ((el = el.previousSibling) && el.nodeType !== 1) {
        // nothing needed here
    }

    return el;
}

function nextElement(el) {
    while ((el = el.nextSibling) && el.nodeType !== 1) {
        // nothing needed here
    }

    return el;
}

Then use the functions like this: 然后使用这样的函数:

do {
    var parent = img.parentNode;
} while (parent && !prevElement(parent) && !nextElement(parent));

If you don't know how many levels up the parent element is, it will be difficult to select it using methods like element.getParent alone. 如果您不知道父元素的级别是多少,则很难使用像element.getParent这样的方法来选择它。 However, you CAN iterate through parent nodes until the node you're looking at has siblings and is the child of a body element. 但是,您可以遍历父节点,直到您正在查看的节点具有兄弟节点并且是body元素的子节点。 Let's assume that your img tag is referred to by imgNode . 我们假设您的img标记由imgNode

function getParentWithSiblings(imgNode) {
    for( ; n; n = imgNode.parentNode) {
        if (n.nextSibling && n.parentNode.tagName == 'body') {
            return n;
       }
    }
}

In the code above, we progressively iterate through the parents of the image node. 在上面的代码中,我们逐步遍历图像节点的父节点。 At each iteration, we check whether the current node (some parent of the img node) has a sibling and is the child of a body tag. 在每次迭代中,我们检查当前节点( img节点的某个父节点)是否具有兄弟节点并且是body标记的子节点。

Just in case you're curious, here's how you might implement user1689607's answer using jQuery . 万一你好奇,这里是你如何使用jQuery实现user1689607的答案

function getAncestorWithSiblings(element) {
  var ancestor = element.parent();
  while (ancestor && ancestor.siblings().length === 0) {
    ancestor = ancestor.parent();
  }
  return ancestor;
}

Whether it makes sense to use this library for your purposes depends on a great deal of context we don't have. 将库用于您的目的是否有意义取决于我们没有的大量背景。 As others have rightfully pointed out, you don't need jQuery to solve this problem, and it may be an unnecessarily heavyweight solution. 正如其他人正确指出的那样,你不需要jQuery来解决这个问题,它可能是一个不必要的重量级解决方案。 That said, it can be a very useful library and is certainly worth your consideration if you weren't aware of it or hadn't already looked into it. 也就是说,它可以是一个非常有用的库,如果您没有意识到它或者还没有对它进行过调查,它肯定值得您考虑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 选择$(this)元素的父级的同级 - Selecting siblings of parent of $(this) element Jstree - 如何获取父节点的子节点(换句话说,如何获取兄弟节点) - Jstree - how to get children of a parent node (in other words, how to get siblings) JavaScript为兄弟姐妹获取父元素和写持有者div - JavaScript get parent element and write holder div for siblings 匹配子节点时获取父元素节点 - Get parent element node when child node is matched 如果父级有边框,当鼠标退出父级和子级时,如何避免来自父级元素的mouseover事件 - How to avoid the mouseover event from the parent element when the mouse is exiting both parent and child if the parent has a border 当父级具有 jQuery 的元素时,如何删除特定元素? - how to remove specific element when parent has an element with jQuery? 当父/主体进行比例转换时,获取元素上的触摸位置 - Get touch position on element when parent/body has scale transformation 如何在 NodeJS 中获取 ElementHandle 的父级和兄弟级? - How do I get parent and siblings of ElementHandle in NodeJS? 父元素的兄弟元素(单击元素除外)在jQuery中消失 - Siblings of parent except element clicked disappear in jQuery 当子元素已知时,如何在 jQuery 中获取父元素? - How to get parent element in jQuery when child element is known?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM