例:
<div someAttr="parentDiv. We need to get it from child.">
<table> ....
<td> <div id="myDiv"></div> </td>
... </table>
</div>
Run Code Online (Sandbox Code Playgroud)
我希望通过内部div元素的某个选择器获取父级(在示例中使用myDiv类).如何在没有jQuery的情况下获得它,只有JS?
就像是:
var div = document.getElementById('myDiv');
div.someParentFindMethod('some selector');
Run Code Online (Sandbox Code Playgroud)
Geo*_*kis 76
您可以closest()在现代浏览器中使用:
var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');
Run Code Online (Sandbox Code Playgroud)
使用对象检测来提供polyfill或替代方法,以便与IE向后兼容.
lee*_*ech 42
查找与给定选择器匹配的最近父级(或元素本身).还包括一个停止搜索的选择器,以防您知道应该停止搜索的共同祖先.
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;
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 34
这是最基本的版本:
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);
Run Code Online (Sandbox Code Playgroud)
通过使用querySelector()和closest()方法可以获取父元素。
querySelector()返回与文档中指定 CSS 选择器匹配的第一个元素。
closest()在 DOM 树中搜索与指定 CSS 选择器匹配的最接近的元素。
const element = document.querySelector('td')
console.log(element.closest('div'))Run Code Online (Sandbox Code Playgroud)
<div>
<table>
<tr>
<td></td>
</tr>
</table>
</div>Run Code Online (Sandbox Code Playgroud)
如果需要选择多个元素,querySelectorAll()是一个不错的选择。
querySelectorAll()以静态 NodeList 对象的形式返回文档中与指定 CSS 选择器匹配的所有元素。要选择所需的元素,需要在内部指定它[],例如第二个元素是:element[1]
在下面的示例中,closest()方法用于获取<tr>特定选定元素的父元素。
const el = document.querySelectorAll('td')
console.log(el[1].closest('tr'))Run Code Online (Sandbox Code Playgroud)
<div>
<table>
<tr id="1">
<td> First text </td>
</tr>
<tr id="2">
<td> Second text </td>
</tr>
</table>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80750 次 |
| 最近记录: |