skip to Main Content

Here I create a Spread Operator with the query selector and want to colour all elements white except the tag, in h1 I want to apply another colour, so here I also applied white colour in h1, so how do I prevent from inheriting white colour? So here I applied the query selector only in div and p tags, but not in h1, so how do I prevent h1 from being white?
enter image description here

  export default function App() {
  const allElements = [...document.querySelectorAll("div", "p")];
  allElements.forEach((element) => {
    console.log(element);
    element.style.backgroundColor = "#0000FF";
    element.style.color = "#fff";
  });
  
  return (
    <div className="App">
      <h1 className="heading">Heading</h1>
      <div>__________________</div>
      <p className="paragraph">paragraph</p>
    </div>
  );
}

2

Answers


  1. the query selector is selecting the <div className="App">, you are applying style on <div className="App"> which makes all child components inherit the style. Hence, making your <h1> white too. I suggest you could use a state to change the style of whichever div or p tags u want. In the code snippet below, you would use setWhiteColor function to change the color of the <div> and <p> to white. This is the react way of doing this.

    const [color, setColor] = useState(false);
    
    const setWhiteColor = () => setColor("white");
    
    return <div className="App">
      <h1 className="heading">Heading</h1>
      <div style={{color: color}}>__________________</div>
      <p style={{color: color}} className="paragraph">paragraph</p>
    </div>
    
    Login or Signup to reply.
  2. If you apply css to parent div, it will automatically apply the styles to children as well. If you want specific elements to not have that style, you will need to override them by giving some styles. Like below

    export default function App() {
      const allElements = [...document.querySelectorAll("div, p")];
      allElements.forEach((element) => {
        element.style.backgroundColor = "#0000FF";
        element.style.color = "#fff";
      });
      
      return (
        <div className="App">
          <h1 className="heading" style={{color: 'initial'}}>Heading</h1>
          <div>__________________</div>
          <p className="paragraph">paragraph</p>
        </div>
      );
    }
    

    Or you can just give it stylesheet file if you don’t want inline.

    .heading { color: initial }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search