我有一个方法findParentByClassName
,它向上查找特定的父类。它工作得很好,但现在我试图返回两个警报,具体取决于1)找不到该名称的parentClass
。 2)它没有父母。这是我到目前为止所做的,但它似乎没有正常工作。
var findParentByClassName = function(element, targetClass) {
if (element.parentElement) {
var currentParent = element.parentElement;
while (currentParent.className != targetClass && currentParent.className !== null) {
currentParent = currentParent.parentElement;
}
if (currentParent === targetClass) ? return currentParent : alert("No parent found with that class name");
} else {
alert("No Parent Element")
}
};
答案 0 :(得分:0)
我个人会用异常替换警报或返回undefined / null,并使用classList属性。
但这是你的代码转换为工作。
您的问题是无效使用了tenery,您还没有检查currentParent是否为空。
我已经更新并添加了findParentByClassName2
,它可以处理具有多个类的父项,如果找不到则返回undefined。
var findParentByClassName = function(element, targetClass) {
if (element.parentElement) {
var currentParent = element.parentElement;
while (currentParent && currentParent.className != targetClass && currentParent.className !== null) {
currentParent = currentParent.parentElement;
}
if (currentParent && (currentParent.className === targetClass)) return currentParent;
alert("No parent found with that class name");
} else {
alert("No Parent Element")
}
};
//a modified version, that will also look for parents
//with multiple classes,..
var findParentByClassName2 = function(element, targetClass) {
element = element ? element.parentElement : null; //skip self
while (element) {
if (element.classList.contains(targetClass)) return element;
element = element.parentElement;
}
}
var a = document.querySelector('.two');
console.log(findParentByClassName(a, 'one'));
console.log(findParentByClassName(a, 'invalid'));
console.log(findParentByClassName2(a, 'one'));
console.log(findParentByClassName2(a, 'invalid'));
<div class="one">
<div class="two">
</div>
</div>