示例:
<div someAttr="parentDiv. We need to get it from child.">
<table> ....
<td> <div id="myDiv"></div> </td>
... </table>
</div>
我希望通过内部div元素的某个选择器获取父级(在 myDiv 类的示例中)。如何获得没有jQuery ,只有JS?
类似的东西:
var div = document.getElementById('myDiv');
div.someParentFindMethod('some selector');
答案 0 :(得分:58)
您可以在现代浏览器中使用closest()
:
var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');
使用对象检测提供polyfill或替代方法,以便与IE进行向后兼容。
答案 1 :(得分:40)
查找与给定选择器匹配的最近父级(或元素本身)。还包括一个停止搜索的选择器,以防您知道应该停止搜索的共同祖先。
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;
}
答案 2 :(得分:33)
这是最基本的版本:
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);
答案 3 :(得分:3)
这是利用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;
}
它并不完美,但如果选择器足够独特,那么它就会无法正常匹配不正确的元素。
答案 4 :(得分:2)
这是一个递归解决方案:
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)
}
答案 5 :(得分:0)
函数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;
};
答案 6 :(得分:0)
我以为我会在打字稿中提供一个更强大的示例,但是转换为纯JavaScript很容易。该函数将使用ID(例如“#my-element”或类“ .my-class”)查询父级,并且与某些答案不同,它将处理多个类。我发现我用类似的方式命名,因此上面的示例发现了错误的内容。
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;
}
let elementByClassName = queryParentElement(someElement,".my-class")
let elementByID = queryParentElement(someElement,"#my-element")
答案 7 :(得分:-2)
var base_element = document.getElementById('__EXAMPLE_ELEMENT__');
for( var found_parent=base_element, i=100; found_parent.parentNode && !(found_parent=found_parent.parentNode).classList.contains('__CLASS_NAME__') && i>0; i-- );
console.log( found_parent );
答案 8 :(得分:-5)
以下是访问父ID
的简单方法document.getElementById("child1").parentNode;
将为您提供访问父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>