[英]Javascript function won't yield expected result
所以我有一个 Javascript 函数应该产生项目的第 n 个孩子。 下面是该函数的代码。
function findNthChild(element) { nthchild = 1; console.log(element); if (element.prev().hasClass('.point')) { while (element.prev().hasClass('.point')) { nthchild++; element == element.prev() } return nthchild; } else { console.log('lmao'); return 1; } }
从你的元素来看,你想要的算法可能看起来像这样
elm
elm
未定义或为null 则返回null
elm
有类InterestClass ,则将n
减1
n
大于0
则返回步骤 1elm
香草,
function nthSiblingElementByClass(sibling, n, cls) {
if (sibling) do {
if (sibling.classList.contains(cls))
if (--n < 0) return sibling;
} while (sibling && (sibling = sibling.nextElementSibling));
return null;
}
用法,例如在此页面上
var elm = document.querySelector('.kwd');
nthSiblingElementByClass(elm, 5, 'pln'); // <span class="pln">console</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.