-1

From the jQuery API Documentation.

.html()
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

How is it determined if this function will match the first element or all the elements that are matched? Consider this html.

<body>
    <p id="simple">The first paragraph</p>
    <p id="simple">The second paragraph</p>
</body>  

If I use the following jQuery

$(document).ready(function() {
    $("p:#simple").html("I changed to this");
});

I will get:

I changed to this
The second paragraph

This result is the same if I change "p:simple" to be "#simple"
However if change the html to use classes instead of ids

<p class="simple">The first paragraph</p>
<p class="simple">The second paragraph</p>  

and change "p:#simple" to be either "p:.simple" or "p" or ".simple" the result will be

I changed to this
I changed to this

Why is this?

b4x
  • 28
  • 6

2 Answers2

0

Your Id must be unique You can learn more about it here: http://www.w3.org/WAI/GL/WCAG20/tests/test185.html

So when you use id selector in jquery it always gets applied to first element found on DOM

If you want to apply your jquery code on multiple elements then you can use class selector or You may use different id's and write the same code for all id's (which is not preferred if you have to use same code on all elements )

And it is not just about .html() function this is applicable for all javasript code

PHP Worm...
  • 4,109
  • 1
  • 25
  • 48
0

Every ID assigned to an element in an HTML page should be unique. Whereas a class can be applied to several elements. JQuery automatically chooses the first element when ID is specified but will select all matching elements when a class selector is used.

Ahs N
  • 8,233
  • 1
  • 28
  • 33