DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Adam Crockett
Adam Crockett

Posted on

Working with DOM in a front end framework?

Now I know this feels like an anti pattern, but when is it okay to use the DOM? I think it is okay to work in the DOM under the following circumstances:

  • what your trying to achieve could be done with `data-β€˜ and you can’t find another way
  • you need to select an element on the page by its location. β€˜document. elementFromPoint(0,0);`
  • any xpath query
  • getting values from css variables into JS
  • it significantly reduces complexity without reducing performance too 🎭

So am I wrong πŸ˜‘?

Top comments (3)

Collapse
 
adam_cyclones profile image
Adam Crockett • Edited on

🧹I should’ve been more specific, VDOM is usually presented in front end frameworks as the way they work and your interaction with the framework will result in interaction with VDOM. We don’t query the DOM directly or use it’s attributes due to performance implications.

Nobody discourages anything but I’d always try to stick to my components and not interact with anything outside of this scope, using the provided API of my chosen framework

Collapse
 
aarone4 profile image
Aaron Reese

Where DOM is a visualisation of application state then in general no, you should not be manipulating DOM directly as the state and visualization can get out of sync. This is one of the reasons jQuery has fallen out of favour; you had to manually update both state and DOM. With modern Frameworks you only update state and the DOM updates automatically. This has perhaps led to the perverse situation where we store stuff in state JUST to update the DOM when we could just have updated DOM directly. Do you really need to store state for whether the side drawer is open? If the button is clicked just add the open class to the container...

Want to rep DEV and be comfy at the same time?

Check out our classic DEV shirt β€” available in multiple colors.