牛XX面试题
1. 封装一个document.getElementById的方法
方案一:
function get(id) { let stack = [document.body]; do{ const current = stack.pop(); // body if(current.getAttribute('id') === id){ return current; }else{ stack = [...stack, ...current.children]; console.log(stack); } }while(stack.length); } // 传递进去id名 var res = get('sum');
方案二:
function getEleById(eleId){ for(var i=0;i<document.all.length;i++){ if(document.all[i].getAttribute('id') == eleId){ return document.all[i]; } } } console.log(getEleById('box'));