简体   繁体   中英

jQuery selector cannot find an element that exists

This doesn't work

var name= "#443.selected:first";
selectedEntity = $(name).attr('entityId');

This works

var name= "li.selected:first";
 selectedEntity = $(name).attr('entityId');

selectedEntity is undefined but an element does exist with id="443" class="selected".

Why doesn't the first example work?

You can use the attribute selector:

$('[id="443"].selected:first')

See this jsFiddle demo

Though in HTML other than HTML5 IDs which start with a number are not allowed, your selector should work ( working Demo ). You must have an error elsewhere in your code and/or markup.

There are several issues you should address:

  1. IDs must be unique otherwise your HTML is invalid
  2. overqualifying the ID-Selector is bad for performance and due to 1) even not necessary
  3. ID-Selectors only return the first element so using :first is useless (and also affected by point 1)
  4. Don't use custom attributes like entityId . Instead use the data- prefix . Then you can use jQuerys data method to get/set those attributes. (Beware however that you cannot use camelCase ).

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