Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

遍历DOM树,拿到每个路径的便签和当前经过的便签的最大data-v的值 #192

Open
TieMuZhen opened this issue May 6, 2022 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

题目

遍历DOM树,拿到每个路径的便签和当前经过的便签的最大data-v的值

<div id="root" data-v="3">
    <p data-v="1">p1</p>
    <span data-v="2">
        <span data-v="4">span2</span>
    </span>
    <p data-v="99">p2</p>
</div>

输出如下

["DIV"] 3
["DIV", "P"] 3
["DIV", "SPAN"] 3
["DIV", "SPAN", "SPAN"] 4
["DIV", "P"] 99

函数入口如下

traverse(document.getElementById('root'));

代码实现

const stack = [];
let maxVal = -Infinity;

function traverse(el){
    stack.push(el.nodeName)
    const data_v = el.getAttribute('data-v');
    if(data_v > maxVal){
        maxVal = data_v;
    }

    const nodes = el.childNodes;
    console.log(stack, maxVal);
    if(!nodes){
        stack.pop();
        return;
    }
    
    nodes.forEach(node => {
        node.nodeType == 1 && traverse(node);
    })
}
traverse(document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant