Home > Software design >  HTML Son element can't rewrite its property if father element has put property onto it
HTML Son element can't rewrite its property if father element has put property onto it

Time:08-08

When I first write the first version, world is still blue. When I modify it to second version, world doesn't turn blue.

The first version use Class" on the <div> tag, I use Class"> <h1>hello</h1> <h1 id="hello">hello</h1> <h1 id="world">world</h1> <script> let hello = document.querySelector("#hello"); let world = document.querySelector("#world"); hello.style.color = null; world.style.color = "unset"; </script> </div>

second version

<div>
    <h1 >hello</h1>
    <h1 id="hello" >hello</h1>
    <h1 id="world" >world</h1>
    <script>
        let hello = document.querySelector("#hello");
        let world = document.querySelector("#world");
        hello.style.color = null;
        world.style.color = "unset";
    </script>
</div>

For the sake of convenience, we usually choose the first version, because it doesn't need to add on every son element tag. However, it will cause the problem mentioned above. Why the problem arises? And is there other way to still use on the father element, and can change son element's property.

CodePudding user response:

The second version can be modified as following in order to have the text colour on world as blue:

<div>
    <h1 >hello</h1>
    <h1 id="hello" >hello</h1>
    <h1 id="world" >world</h1>
    <script>
        let hello = document.querySelector("#hello");
        let world = document.querySelector("#world");
        hello.style.color = null;
    </script>
</div>

Setting world.style.color = "unset"; in first case was setting #world element colour to the inherited color value from parent, which was blue.

The initial value for color property is expected to be black, which is what setting color to unset in the second case would apply.

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/unset

CodePudding user response:

use the keyword initial instead of unset to achieve what you want.

        let hello = document.querySelector("#hello");
        let world = document.querySelector("#world");
        hello.style.color = null;
        world.style.color = "initial";
.Class{
  color:blue;
  }
<div >
    <h1>hello</h1>
    <h1 id="hello">hello</h1>
    <h1 id="world">world</h1>
</div>

  • Related