| |

VerySource

 Forgot password?
 Register
Search
View: 1567|Reply: 3

DOM child node comparison problem?

[Copy link]

2

Threads

6

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 United States

Post time: 2020-12-25 10:00:01
| Show all posts |Read mode
<html>
<head><title>Test</title>
<script type="text/javascript">
function nodecheck(parentNode,childNode)
{
var childs=parentNode.childNodes;
for(var i=0;i<childs.length;i++)
{
if(childs[i]==childNode)
return true;
if(childs[i].hasChildNodes())
nodecheck(childs[i],childNode);
}
return false;
}
var testfun=function()
{
var e1=document.getElementById('ROOT');
var e2=document.getElementById('A');
alert(nodecheck(e1,e2));
}
</script>
</head>
<body onload="testfun();">
<div id="ROOT">
<div id="A">
<div id="AA">
<div id="AAA">
Hello
</div>
</div>
</div>
<div id="B">
<p id="BA">
<input id="BAA" type="text" />
</p>
<p id="BB">
<input id="BBA" type="button" value="lala" />
</p>
</div>
<div id="C">
<select id="CA">
<option id="CAA">1</option>
<option id="CAB">2</option>
<option id="CAC">3</option>
</select>
</div>
</div>
</body>
</html>
================================================= ============
Purpose: Enter a node A, and then enter a node B, to determine whether node B is a child node of node A
Yes return true, no return false

var e1=document.getElementById('ROOT');
var e2=document.getElementById('A');
Return true A is a child node of ROOT

var e1=document.getElementById('ROOT');
var e2=document.getElementById('AA');

Why return false?
Is this comparison judging that there is a problem with childs[i]==childNode?
Reply

Use magic Report

0

Threads

9

Posts

7.00

Credits

Newbie

Rank: 1

Credits
7.00

 China

Post time: 2020-12-25 11:15:01
| Show all posts
Use traversal
Determine whether B is a child node of A

function isChild(A,B){
    for(var i=0;i<A.childNodes.length;i++){
        if(A.childNodes[i]==B){
            return true;
        }
    }
    return false;
}
Reply

Use magic Report

0

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-12-25 11:30:01
| Show all posts
var testfun = function()
       {
            var e1 = document.getElementById('ROOT');
            var e2 = document.getElementById('A');
            while (e2.parentNode) {
                if (e2 == e1)
                    return true;
                e2 = e2.parentNode;
            }
            return false;
        }
It's easier to judge this way
Reply

Use magic Report

2

Threads

6

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

 Author| Post time: 2020-12-25 11:45:01
| Show all posts
Reverse judgment. It’s a good way to turn one-to-many into one-to-one. Not bad
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list