Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i apply jquery on all elements with same id attribute?

Tags:

jquery

How can i apply jquery on all elements with same id attribute ?

i want to apply a focus() and blur() function on a textarea elements that have same id?

like image 571
Azfar Niaz Avatar asked Oct 27 '10 16:10

Azfar Niaz


People also ask

How do I select all elements with the same ID?

In simple way if you use id to select all div having same ids then it will select first id only but if you want to select ,want go through each div or any other element with same id then I will explain you how you can do that. $( '#red' ). css( 'background-color' , 'red' ); $( '#green' ).

What happens if multiple elements have the same ID?

The id must be unique. There can be only one element in the document with the given id . If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document. getElementById may return any of such elements at random.

Can you have two divs with the same ID?

As HTML and CSS are designed to be very fault tolerant, most browsers will in fact apply the specified styles to all elements given the same id. However, this is considered bad practice as it defies the W3C spec. Applying the same id to multiple elements is invalid HTML and should be avoided.


1 Answers

The right answer would be

$("[id=yourID]").doSomething()

for any code like

<textarea id="yourID" />
<img id="yourID" />
<div id="yourID" />

yes, i know, this is not valid html but note that we middle-class-developers often have to deal with problems "better" developers made. Check out Microsoft SharePoint for example, where multiple IDs are very common. And we cannot tell our customers that Microsoft did poorly so we cannot help them. We tell them Microsoft did poorly so we have to help them;-)

like image 102
efkah Avatar answered Oct 23 '22 19:10

efkah