我的思路是使用遞歸,一層層往上找。判斷元素名是DIV就返回。下面是我寫的一部分,但實(shí)現(xiàn)不了。求大神幫忙。function findDiv(dom) {? ? ? ? var result = [];? ? ? ? var parents = dom.parentNode;? ? ? ? if (parents.nodeName.toUpperCase() === "BODY") {? ? ? ? ? ? return;? ? ? ? } else if (parents.nodeName.toUpperCase() === "DIV") {? ? ? ? ? ? result.push(parents.nodeName);? ? ? ? }? ? ? ? // console.log(result);? ? ? ? return result;? ? }
JS面試題:寫一個(gè)方法,傳入一個(gè)DOM元素,找到它所有祖先元素中div的個(gè)數(shù),并返回。
lxfawh
2017-05-10 18:18:09