Reputation: 45
In my page, due to some reason (which I do not find relevant to the topic hence not explaining) a div gets duplicated and two divs with same id are generated in my html. While writing jquery code to remove all divs except topmost, I found that $("#id")
was returning me just 1 element(note: there are two divs with same id now) whereas $("[id=]")
was returning me 2
. So finally my code worked with $("[id=]")
but not with $("#id")
.
Any reason why? Is it that $("#id")
returns only the first element it finds with specified id?
Please note that I have already come across a thread which has a similar question but does not answer my query
Upvotes: 2
Views: 4761
Reputation: 281864
The thing is $("#id")
will always gives you single result like document.getelementById()
however when you do $("[id=]")
you are finding all elements with a given attibute as id
so it returns you multiple elements since it doesn't use the javascript document.getelementById()
now.
$("[id=]")
is something that you use when you want to select some elements form your document that follow some rules like
Attribute Contains Selector [name*=”value”]
Selects elements that have the specified attribute with a value containing a given substring.
Attribute Contains Word Selector [name~=”value”]
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.
Attribute Ends With Selector [name$=”value”]
Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.
etc.
For more information see https://api.jquery.com/category/selectors/
However in you HTML you should ideally keep the id
to be unique. If you want multiple elements to have same id then use class
instead.
Upvotes: 4