You don't have to duplicate ID to handle your case. You can use class selector to select the element with context. Which is much cleaner in many ways. See below,
//will select element with class .Genders inside #tableFor_SEARCH
$(".Genders", "#tableFor_SEARCH").buttonset();
//will select element with class .Genders inside #tableFor_CREATE
$(".Genders", "#tableFor_CREATE").buttonset();
Why you should NOT duplicate ID?
The ID attribute should be unique and that is the standard. http://www.w3.org/TR/html401/struct/global.html#h-7.5.2 .The purpose of ID attribute is to identify an element uniquely in a page. This purpose is defeated when you duplicate it.
Below is the list of reason why you should not duplicate an ID,
- It is not a standard. http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
- It is broken. http://jsfiddle.net/8H2Da/1/ [with or without context, it would just get the first matching element]
- Accessing an element with duplicate ID using context is slow, well for that fact ID selector is the fastest of any selector. http://jsperf.com/jquery-id-selector-with-context/2
- You cannot tag second duplicate ID element from the URL. http://fiddle.jshell.net/s27hQ/show/light/#Goto3 [Note the last part
#Goto3
of the URL]
- You cannot create local link
<a href="#dupId">Go to That element</a>
to navigate to second duplicate ID element. http://jsfiddle.net/s27hQ/
How it works in jQuery?
$('#Genders')
simply calls document.getElementById('Genders')
and wraps it with a jQuery object.
However when you do $("#Genders", $("#tableFor_SEARCH"))
, it simply cannot use getElementById
, internally jQuery is going to iterate over every element inside #tableFor_SEARCH
to find the matching element with ID #Genders
.
Why browser doesn't complain?
From HTML stand point, ID attribute is used to tag the element in a page which you can use as navigate to element using a local page link http://jsfiddle.net/s27hQ/ or navigate to that section from the URL http://fiddle.jshell.net/s27hQ/show/light/#Goto3
Browsers are flexible and forgiving with the developers, even a sloppy HTML code will be rendered beautifully in most desktop browsers. Same way, it really doesn't complain about having duplicate ID, but also it really doesn't work either. Item #4 and #5 from the above.
From JavaScript standpoint, ID element can be accessed using document.getElementById
a native, coolest, fastest, one of the oldest API to access an element uniquely in a page. Which clearly doesn't provide a way to access second element with a duplicate ID.
So please don't use it.
Make it a better and easily maintainable code for the future developers.
.add()
, are you looking to select multiples of the same ID from different scopes within the page? Then$('#id1').add('#id2').find('#WhatIWant')
is probably what you want. However, it's near impossible to tell what you're looking for, and what exactly a credible/official source is for you.