简体   繁体   中英

Javascript function won't yield expected result

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

  1. Look at the next sibling element, elm
  2. If elm is undefined or null return null
  3. If elm has class interestingClass , decrease n by 1
  4. If n is greater than 0 go back to step 1
  5. Return 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>​

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM