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?
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
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.
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
Or you can just give it stylesheet file if you don’t want inline.