Home > other >  IF returns false but should return true
IF returns false but should return true

Time:01-12

HTML:

    <div  id="1" onclick="test()">  </div>
    <div  id="2" onclick="test()">  </div>
    <div  id="3" onclick="test()">  </div>
    <div  id="4" onclick="test()">  </div>

JS:

{
        document.getElementById(e.target.id).appendChild(document.NewDiv("div", {id:"element1"}));

        if (document.getElementById("1").contains(document.getElementById("element1")) &&
            document.getElementById("2").contains(document.getElementById("element1")))
        {
            console.log("yes")
        }
        else
        {
            console.log("no")
        }
    };

This code returns "no" when element1 is in containers with id 1 and 2 but in my meaning it should be "yes"

But this code returns "yes" as should it be - if element1 is present in at least one of the two containers

    {
        document.getElementById(e.target.id).appendChild(document.NewDiv("div", {id:"element1"}));

        if (document.getElementById("1").contains(document.getElementById("element1")) || //<-- changed
            document.getElementById("2").contains(document.getElementById("element1")))
        {
            console.log("yes")
        }
        else
        {
            console.log("no")
        }
    };

I want this code to return "yes" if element1 is in container 1 and 2

    {
        document.getElementById(e.target.id).appendChild(document.NewDiv("div", {id:"element1"}));

        if (document.getElementById("1").contains(document.getElementById("element1")) &&
            document.getElementById("2").contains(document.getElementById("element1")))
        {
            console.log("yes");
        }
        else
        {
            console.log("no");
        }
    };

CodePudding user response:

You can't have the same element in two different containers. Therefore the && condition can't be true, while || can.

id attribute must be unique, you should not have more than one element with the same id in the same document. If you happened to have multiple elements with the same id, only the first element can be selected with document.getElementById().

However, theoretically you could use myelement.querySelector('[id="element1"]') to get element with id in the myelement container, but you should fix the code by not using the same ids.

        if (document.getElementById("1").contains(document.getElementById("1").querySelector("[id='element1']")) &&
            document.getElementById("2").contains(document.getElementById("2").querySelector("[id='element1']"))))
        {
            console.log("yes")
        }
        else
        {
            console.log("no")
        }
  • Related