0

After clicking the button, does jQuery traverse the DOM from the root again or is the child element cached? Will doing something like var childElement = $('.child') always make it possible to access the child element directly? Is saving a jQuery object in a variable practiced by developers?

$('button').click(function() {
  $('.child').append('Text. ');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Add text</button>

<div class="parent5">
  <div class="parent4">
    <div class="parent3">
      <div class="parent2">
        <div class="parent1">
          <div class="child">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
noob_coder
  • 35
  • 2
  • 7
  • 1
    Yes you should cache the element. Many prepend the jQuery variable with a $, as in `const $childElements = $('.child')` - I write childElements plural, because jQuery will take anything with class child. If there is only ONE child, use ID to document that – mplungjan Aug 23 '21 at 05:57
  • 1
    Don’t forget that you can chain most method calls: `$(".child").append("Text. ").fadeIn(300).on("click", console.log).wrap("
    ");` etc.
    – Sebastian Simon Aug 23 '21 at 06:00
  • I'm not sure exactly if it _"traverses the DOM"_ every time. Some lookups such as by `id` or `class` may be indexed by the browser but this would be implementation specific and nothing to do with jQuery. The general advice given above is best practice though – Phil Aug 23 '21 at 06:03

0 Answers0