简体   繁体   中英

Get DOM Element with jQuery

I have a web page that is structured like this:

  <canvas id="myCanvas"></canvas>

  @for(var i=0; i<10; i++) {
    <div class="my-element">
      <canvas></canvas>
    </div>
  }

This code generates one main canvas. Below it, 10 other dynamically generated divs are being generated. In reality, this loop is just used to show that I have some code being dynamically generated. The main thing to understand is the my-element piece.

In my javascript, I have the following:

$(function() {
  var mainCanvas = document.getElementById('myCanvas');
  initializeCanvas(mainCanvas);  // This works.

  var dynamicElements = $('.my-element');
  for (var i=0; i<dynamicElements.length; i++) {
    initializeCanvas($(dynamicElements[i])[0]);   // This does not work
  }
});

function initializeCanvas(canvas) {
  // do stuff
}

The first call to initializeCanvas works because I'm passing in an actual HTML Dom element. But the second initializeCanvas , which is called multiple times, fails because it's passing in something else. How do I get the same type of element as what's returned by document.getElementById in this case?

Thanks!

First of all, this doesn't make sense: $(dynamicElements[i])[0]

You are getting jQuery element, unwrapping it, then wrapping again in jQuery...

what you simply need to do is get canvas from the element

dynamicElements.eq(i).find('canvas')[0] should do the job

You can't use the same element for this purpose. I suggest you to clone it. Like;

 var dynamicElements = $('.my-element').clone();

Also when you add more element with my-element class this will be messy. You should make sure to select only one element with $('.my-element') selection.

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