Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice in finding a DOM element

I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:

  1. Find the element according to its class name, e.g $('.my-content')

  2. Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()

However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?

like image 383
Unknown developer Avatar asked Oct 25 '25 12:10

Unknown developer


2 Answers

A very good practice is to decouple HTML, CSS and JS.

When binding javascript to DOM elements you should use javascript selectors. Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).

So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector

HTML

<div class="my-content js-toggle-element"></div>

JS

$('.js-toggle-element')

CSS

.my-content{ ... }

Plus, using Javascript Selectors:

  • makes HTML highly readable: you can easily find out what will happen to that element with that js class
  • allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all

    <div class="my-content js-toggle-element"></div>
    ...
    <div class="another-content-to-toggle js-toggle-element"></div>
    
like image 117
pumpkinzzz Avatar answered Oct 27 '25 03:10

pumpkinzzz


  1. If it's a specific element, supply it with an Id value and use that to find it.
  2. If it's a TYPE of element, use a class name.

Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.

like image 30
FvB Avatar answered Oct 27 '25 03:10

FvB