js使用深度优先遍历实现getElmentById(id)
生活随笔
收集整理的這篇文章主要介紹了
js使用深度优先遍历实现getElmentById(id)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
function getElementById(node, id) {if (!node) return null;if (node.id === id) return node;for (var i = 0; i < node.childNodes.length; i++) {var found = getElementById(node.childNodes[i], id);if (found) return found;}return null;}
測試情況。
這里是使用遞歸的方法來實現id 的選擇。
使用遞歸代碼簡單,但是性能上比不上非遞歸的實現,Chrome 瀏覽器的DOM查找就是使用的非遞歸。
function getElementById(node, id) {while (node) {if (node.id === id) return node;node = nextElement(node)}}function nextElement(node) {if (node.children.length) {return node.children[0];}if (node.nextElementSibling) {return node.nextElmentSibling;}while (node.parentNode) {if (node.parentNode.nextElementSibling) {return node.parentNode.nextElementSibling;}node = node.parentNode;}return null}總結
以上是生活随笔為你收集整理的js使用深度优先遍历实现getElmentById(id)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【深度学习】ICCV2021|性能优于何
- 下一篇: mingw64+msys2下使用cmak