Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting by element ID + element class yields same element twice

Why is jQuery returning same element twice here?

Checked the HTML numerous times, there's only one <div> with id="3" and class="password_field_real".

This is the result for getting all elements with class="password_field_real":

> $(".password_field_real")

[
    <div class="password_field_real" id="2" style="display: none;"></div>, 
    <div class="password_field_real" id="3" style="display: none;"></div>,
    <div class="password_field_real" id="7" style="display: none;"></div>,
]

However, when I try to get class="password_field_real" and id="3", I get a list of two divs, which are the same!

> $("#3.password_field_real")

[
    <div class="password_field_real" id="3" style="display: none;"></div>,  
    <div class="password_field_real" id="3" style="display: none;"></div>
]

This is not the case with other two divs:

> $("#7.password_field_real")

[
    <div class="password_field_real" id="7" style="display: none;"></div>
]

Why could this happen?

* UPDATE *

Reproduced this in jsFiddle

* UPDATE #2 *

If non-numeric ID's are used, everything works just fine.

like image 817
dusty Avatar asked Mar 03 '13 12:03

dusty


2 Answers

First of all, an id must be unique on a page. That is the idea behind it.

Your problem is that you use an invalid ID selector (according to HTML4):

  1. ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

In other doctypes there are different restrictions, but you always need at least one letter. Since you only use a number, it is invalid. That might be the explanation when you use non-numeric ID's everythings fine. Still it's a bit weird behaviour of jQuery.

Prepend your ID's with at least one letter [A-Za-z], or even better, make it descriptive.

like image 63
Justus Romijn Avatar answered Nov 03 '22 00:11

Justus Romijn


NEVER use multiple time the same id, id MUST be UNIQUE

alert( $("#3").length ); // will just return 1 not 8

this really dumb code just select your good one, but never use that, will cause end of world

alert( $("#3").find("#3").filter(".password_field_real").attr("class") );

if you need current id for each sub "div" and "a", try data- with why not a code like that

$(".password_entry").each(function(){
    var $t = $(this);
    var currentId = $t.attr("id");
    $t.find("div,a").data("id",currentId);
});

now you can extract current id from all sub "div" and "a" with .data("id")

by exemple :

$(".password_field_mask").click(function(){ alert( $(this).data("id") ); });
like image 31
r043v Avatar answered Nov 03 '22 01:11

r043v