JavaScript:如何通过选择器获取父元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14234560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:06:40  来源:igfitidea点击:

JavaScript: How to get parent element by selector?

javascriptdom

提问by nkuhta

Example:

例子:

<div someAttr="parentDiv. We need to get it from child.">
    <table> ....
        <td> <div id="myDiv"></div> </td>
    ... </table>
</div>

I want to get parent by some selector from inner div element (in example with myDivclass). How to get it WITHOUT jQuery, only JS?

我想通过一些选择器从内部 div 元素(在myDiv类的示例中)获取父级。如何在没有 jQuery 的情况下获得它,只有 JS?

Something like:

就像是:

var div = document.getElementById('myDiv');
div.someParentFindMethod('some selector');

采纳答案by Chris

Here's the most basic version:

这是最基本的版本:

function collectionHas(a, b) { //helper function (see below)
    for(var i = 0, len = a.length; i < len; i ++) {
        if(a[i] == b) return true;
    }
    return false;
}
function findParentBySelector(elm, selector) {
    var all = document.querySelectorAll(selector);
    var cur = elm.parentNode;
    while(cur && !collectionHas(all, cur)) { //keep going up until you find a match
        cur = cur.parentNode; //go up
    }
    return cur; //will return null if not found
}

var yourElm = document.getElementById("yourElm"); //div in your original code
var selector = ".yes";
var parent = findParentBySelector(yourElm, selector);

回答by George Kargakis

You may use closest()in modern browsers:

您可以closest()在现代浏览器中使用:

var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');

Use object detection to supply a polyfillor alternative method for backwards compatability with IE.

使用对象检测提供一种polyfill或替代方法,以实现与 IE 的向后兼容。

回答by leech

Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.

查找与给定选择器匹配的最近父元素(或元素本身)。还包括一个停止搜索的选择器,以防您知道应该停止搜索的共同祖先。

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.matches(selector)) {
      retval = el;
      break
    } else if (stopSelector && el.matches(stopSelector)) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

回答by Trevor Nestman

Using leech's answer with indexOf (to support IE)

使用带有 indexOf 的 leech 答案(以支持 IE)

This is using what leech talked about, but making it work for IE (IE doesn't support matches):

这是使用 leech 所说的,但使其适用于 IE(IE 不支持匹配):

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.className.indexOf(selector) > -1) {
      retval = el;
      break
    } else if (stopSelector && el.className.indexOf(stopSelector) > -1) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

It's not perfect, but it works if the selector is unique enough so it won't accidentally match the incorrect element.

它并不完美,但如果选择器足够独特,它就可以工作,这样它就不会意外匹配不正确的元素。

回答by Cully

Here's a recursive solution:

这是一个递归解决方案:

function closest(el, selector, stopSelector) {
  if(!el || !el.parentElement) return null
  else if(stopSelector && el.parentElement.matches(stopSelector)) return null
  else if(el.parentElement.matches(selector)) return el.parentElement
  else return closest(el.parentElement, selector, stopSelector)
}

回答by Joel Teply

I thought I would provide a much more robust example, also in typescript, but it would be easy to convert to pure javascript. This function will query parents using either the ID like so "#my-element" or the class ".my-class" and unlike some of these answers will handle multiple classes. I found I named some similarly and so the examples above were finding the wrong things.

我想我会提供一个更健壮的例子,也在打字稿中,但很容易转换为纯 javascript。此函数将使用“#my-element”或类“.my-class”之类的 ID 查询父项,与其中一些答案不同的是,它将处理多个类。我发现我命名了一些类似的东西,所以上面的例子找到了错误的东西。

function queryParentElement(el:HTMLElement | null, selector:string) {
    let isIDSelector = selector.indexOf("#") === 0
    if (selector.indexOf('.') === 0 || selector.indexOf('#') === 0) {
        selector = selector.slice(1)
    }
    while (el) {
        if (isIDSelector) {
            if (el.id === selector) {
                return el
            }
        }
        else if (el.classList.contains(selector)) {
            return el;
        }
        el = el.parentElement;
    }
    return null;
}

To select by class name:

按班级名称选择:

let elementByClassName = queryParentElement(someElement,".my-class")

let elementByClassName = queryParentElement(someElement,".my-class")

To select by ID:

按 ID 选择:

let elementByID = queryParentElement(someElement,"#my-element")

let elementByID = queryParentElement(someElement,"#my-element")

回答by Sergio Belevskij

simple example of a function parent_by_selector which return a parent or null (no selector matches):

函数 parent_by_selector 的简单示例,它返回父级或 null(没有选择器匹配):

function parent_by_selector(node, selector, stop_selector = 'body') {
  var parent = node.parentNode;
  while (true) {
    if (parent.matches(stop_selector)) break;
    if (parent.matches(selector)) break;
    parent = parent.parentNode; // get upper parent and check again
  }
  if (parent.matches(stop_selector)) parent = null; // when parent is a tag 'body' -> parent not found
  return parent;
};

回答by ameya rote

Here is simple way to access parent id

这是访问父ID的简单方法

document.getElementById("child1").parentNode;

will do the magic for you to access the parent div.

将为您提供访问父 div 的魔法。

<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>