So I have a Javascript function that is supposed to yield the item's nth child. 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
is undefined or null return null
elm
has class interestingClass , decrease n
by 1
n
is greater than 0
go back to step 1elm
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.