元素遍历
跨浏览器遍历某元素的所有子元素
1 2 3 4 5 6 7 8 9
| var i, len, child = element.firstChild; while(child != element.lastChild) { if (child.nodeType == 1) { processChild(child); } child = child.nextSibling; }
|
而使用 Element Traversal(IE 9+) 新增的元素,代码会更简洁
1 2 3 4 5 6 7
| var i, len, child = element.firstElementChild; while(child != element.lastElementChild) { processChild(child); child = child.nextElementSbling; }
|
删除类名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <div class="bd user disabled"></div> //删除"user"类 //首先,取得类名字符串并拆分成数组 var classNames = div.className.split(/\s/); //找到要删除的类名 var pos = -1, i, len; for (i=0, len=classNames.length; i < len; i++) { if (classNames[i] == "user") { pos = i; break; } } //删除类名 classNames.splice(pos,1); //把剩下的类名拼成字符串并重新设置 div.className = classNames.join(" ");
|
HTML5
跨浏览器兼容 innerText
1 2 3 4 5 6 7
| function setInnerText(element, text) { if (typeof element.textContent == "string") { element.textContent = text; //兼容 Firefox } else { element.innerText = text; } }
|