Get widget without id

Asked

Viewed 200 times

5

I have a div, and within it one canvas without id and other elements.

<div id="itens">
   ...
   <canvas></canvas>
   ...
</div>

How can I get the canvas using JQuery?

  • 2

    $("#canvas items") or Document.getelementsbytagname("canvas") would be that only ?

  • @Thiagofriedman, format in response your comment! :)

  • The only problem is that in both cases they don’t bring the canvas object itself. In the first case, it brings a jquery object with a canvas array, in the second case it also brings a canvas array, so if I have var canvas = document.getElementsByTagName("canvas"); to be able to work with the canvas obtained should I use canvas[0]. I would like something to bring me the first canvas at once.

  • 1

    get the canvas array can be useful if you want to assign a style, or other property to all canvas at once

  • @Pedrolaini, you are right! In this case would work perfectly the two options very well given by Thiagofriedman, but in my case there is only one canvas, and I need to work with its properties, so the answer posted by Pedrolaini solved my problem.

1 answer

4


If you need the canvas inside the element #itens

1) $('#itens canvas') selects all the canvas within the element $itens

2a) To return only the first (or single) utilize $('#itens canvas').get(0) or $('#itens canvas')[0]

2b) Or, as suggested by @Jefersonassis in the comments:

$('#canvas items:first-Child')

If you want all the canvas elements

1) $('canvas') selects all canvas on the page

2a) To return only the first (or single) utilize $('canvas').get(0) or $('canvas')[0]

2b) Or, as suggested by @Jefersonassis in the comments:

$('#canvas items:first-Child')

  • And if I only want to get the first canvas?

  • 1

    answered the question

  • 2

    Just by complementing Pedro’s response, you can use the selectors :first-child, would look like this: $('#itens canvas:first-child').

  • included in the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.