Home > OS >  Components affect each other in Svelte
Components affect each other in Svelte

Time:03-20

I'm a beginner learning the web.

While I was studying the web, I realized that if the id is the same among the components, it has an effect each others.

I know I need to use a unique id, but I don't know how to use in css.

I linked the demo page.

The text may be weird, because i'm using a translator. I'm sorry.

CodePudding user response:

The problem is caused because you call the querySelector on the whole document which contains all the elements. So it wil find 2 elements with the id testDiv and because it doesn't know which one you want it just takes the first. You can fix this by not using document.querySelector but binding the element itself to a variable whitin the component so that you don't have to find the html element but have a reference inside the component that is always pointing to the correct element. Example:

https://svelte.dev/repl/cfa458ef45de466aa9421705f49cc95e?version=3.46.4

Here is also a related question if you want to read into it more: How to scope querySelector to component in Svelte?

  • Related