简体   繁体   中英

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, eg $('.my-content')

  2. Find the element according to its relevant DOM position towards the button, eg $('#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?

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> 
  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.

Using jQuery will be much easiest way. Like this -

$( ".target" ).toggle();

The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.

Reference - jQuery Toggle

如果元素的类或元素在DOM中的位置正在更改,则可以尝试使用内部文本选择它

$("button:contains('buttontextgoeshere')")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM