[英]Javascript function won't yield expected result
So I have a Javascript function that is supposed to yield the item's nth child.所以我有一个 Javascript 函数应该产生项目的第 n 个孩子。 Below is the code for the function.
下面是该函数的代码。
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; } }
From your element, the algorithm you want might look something like this从你的元素来看,你想要的算法可能看起来像这样
elm
elm
elm
is undefined or null return null
elm
未定义或为null 则返回null
elm
has class interestingClass , decrease n
by 1
elm
有类InterestClass ,则将n
减1
n
is greater than 0
go back to step 1n
大于0
则返回步骤 1elm
elm
Vanilla,香草,
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;
}
Usage, eg on this page用法,例如在此页面上
var elm = document.querySelector('.kwd');
nthSiblingElementByClass(elm, 5, 'pln'); // <span class="pln">console</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.