我已引用一个元素baseElement
,并且我想查找某些HTML数据属性在其祖先之一的某个位置是否存在,并获取它的值(如果找到)。如果该属性存在于多个祖先上,那么我只想将该属性放在最紧密相关的祖先上。
我设计了一个循环,该循环由父母决定,并检查该属性是否存在。假定baseElement
的第一个父级不为null。
let currentElement = baseElement.parentElement;
let foundAttribute = false;
let valueOfAttribute = null;
do {
foundAttribute = currentElement.hasAttribute('html-attribute');
if (foundAttribute) {
valueOfAttribute = currentElement.getAttribute('html-attribute');
} else {
currentElement = currentElement.parentElement;
}
} while (!foundAttribute && currentElement);
我想看看是否有更有效,更雄辩或更易于编码的方式来做到这一点。请只提供纯JavaScript答案。
亲爱的,我有一种更简单的方法。
closest()
[let ancestor = baseElement.closest('[html-attribute]');
let attr_val = ancestor ? ancestor.getAttribute('html-attribute') : null;
具有选择器,就像closest()
和类似方法。