简体   繁体   中英

Select specific element type with specific ID in jQuery

I want to find any canvas elements with the id whatever using jQuery. I thought I could do $('canvas #whatever') but that doesn't return anything when I have a canvas with that id on the page.

Your selector will return an element that is a canvas's child. Doing $('#whatever') should already return what you expect, since IDs should be unique in a page.

Anyway, if you really want to be more specific, the correct way to retrieve a canvas with this ID is to remove your space there: $('canvas#whatever')

Try this, $('canvas#whatever')

This should work.

if you want multiple elements with the same identifier use classes and then reference it $("canvas .yourclass"). I'm not sure if thats what's causing your issue but if its not a unique ID it's not right.

Try class = whatever instead, seems to work better. Canvases with the same Id behave strangely.

 $('.whatever').css('background-color','green'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas class="whatever" width="50px" height="50px"></canvas> <canvas class="whatever" width="50px" height="50px"></canvas> <canvas class="whatever" width="50px" height="50px"></canvas> 

The empty space you leave after the element type implies that the following selector concerns children of that element. You need to keep the whole selector tight together, no spaces.

$('canvas#whatever')

Try this

$('canvas#whatever')

or

$('canvas[id=whatever]')

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