Jquery Id Selector Works Only For the First Element

jQuery ID selector works only for the first element

I have 3 buttons with same id ...

You have invalid HTML. You can't have more than one element in a page with the same id attribute value.

Quoting the spec:

7.5.2 Element identifiers: the id and class attributes

id = name [CS]

This attribute assigns a name to an element. This name must be unique in a document.

Solution: change from id to class:

<button type="button" class="btn btn-primary xyz" value="1">XYZ1</button>
<button type="button" class="btn btn-primary xyz" value="2">XYZ2</button>
<button type="button" class="btn btn-primary xyz" value="3">XYZ3</button>

And the jQuery code:

$(".xyz").click(function(){
alert(this.value);
// No need for jQuery :$(this).val() to get the value of the input.
});

But it works only for the first button

jQuery #id selector docs:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

If you look at the jQuery source you can see when you call $ with an id selecor-($("#id")), jQuery calls the native javascript document.getElementById function:

// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
}

Though, in the spec of document.getElementById they didn't mention it must return the first value, this is how most of (maybe all?) the browsers implemented it.

DEMO

My script only works on the first element with an ID

Every ID for an HTML element must be unique. Use classes instead.

<div class="block">
<img class="cimg" src="http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

<div class="block">
<img class="cimg" src="http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

<div class="block">
<img class="cimg" src="http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

And

var rgb;
var imgg = document.getElementsByClassName("cimg");
var blocks = document.getElementsByClassName("block");
var i;
for (i = 0; i < imgg.length; i++) {
rgb = averageColor(imgg[i]);

blocks[i].style.backgroundColor =
'rgb(' + rgb.r + ','
+ rgb.g + ','
+ rgb.b + ')';
}

Iteration in javascript only returns the first element

However, the code snippet above only returns the first item qtdPersonalizacao within the first personalizacoesOpcionais.

Ids are supposed to be unique within a document and jQuery will just returns the first matching element.

The recommended solution would be to use a class instead of an id for personalizacoesOpcionais.

If this is not possible, for example if you don't control the code that generate the markup, a workaround would be to use $("div[id=personalizacoesOpcionais]") instead of $("#personalizacoesOpcionais")

Why does Jquery only affect the first div element?

You have duplicate ids, Which is invalid and also jQuery ID selector(or any other id selector like document.getElementById which internally jQuery uses because element with ids are indexed by most browsers and are meant to be unique) will return only the first one that appears in DOM. Change it to class and see it working:

$('.comment').each(function() { 
var thz = $(this); var repl =
thz.html(thz.html().replace(/\D+/g, ''));
});

HTML

<a class="comment1" href="#"> c2fđf011. </a> 
<a class="comment1" href="#">c20ff113. </a>
<a class="comment1" href="#"> c201gf76341. </a>

By the way had your id been like this:-

<a id="comment1" href="#"> c2fđf011. </a> 
<a id="comment2" href="#">c20ff113. </a>
<a id="comment3" href="#"> c201gf76341. </a>

Starts with Attribute selector will help you (But slow you down literally, since this is an attribute selector and lose the advantage of using IDs).

$('[id^=comment]').each(function() { // While using this better give a container context $('[id^=comment]', 'container').each(function...
var thz = $(this);
var repl = thz.html(thz.html().replace(/\D+/g, ''));
});

Demo

Moral: IDs must be unique

$(#id) only selects the first element but $(div#id) selects both?

Explanation for jQuery

Also, in your case, jQuery should select only one element, and the first element for ID. Since you have also given div, it uses getElementsByTagName, and matches the attribute with ID. So, it returns all the instances. Please correct me if I am wrong.

Suggestion

According to web standards, the id attribute must be unique. So, each element should have unique ID. If you want to use things for multiple elements, you have classes.

Also, your HTML won't validate, if you have multiple IDs.

Also, from the XHTML 1.0 Spec

In XML, fragment identifiers are of
type ID, and there can only be a
single attribute of type ID per
element. Therefore, in XHTML 1.0 the
id attribute is defined to be of type
ID. In order to ensure that XHTML 1.0
documents are well-structured XML
documents, XHTML 1.0 documents MUST
use the id attribute when defining
fragment identifiers on the elements
listed above. See the HTML
Compatibility Guidelines for
information on ensuring such anchors
are backward compatible when serving
XHTML documents as media type
text/html.

jQuery click function only works on first element

In HTML, id refers to a unique identifier. In other words, it is against standards to have 2 elements with the same id. jQuery here behaves correctly.

Use a class instead of an id to identify your tags as such:

HTML:

<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a class="edit" href="#">edit</a>
<span id="title">List item 1</span>
</li>

<li class="sortable" id="listItem_2">
<a class="edit" href="#">edit</a>
<span id="title">List item 2</span>
</li>

etc..
</ul>

JavaScript:

$(document).ready(function() {
$('a.edit').click(function(){
alert($(this).parent("li").attr("id"));
})
});

Alternatively, since the parent tag already seems to have a unique class, you could simply use it to target wanted tags. This would reduce what I call "class noise" (the defining of useless class to target element which could be targeted by their parent's unique attributes).

HTML:

<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a href="#">edit</a>
<span id="title">List item 1</span>
</li>

<li class="sortable" id="listItem_2">
<a href="#">edit</a>
<span id="title">List item 2</span>
</li>

etc..
</ul>

JavaScript:

$(document).ready(function() {
$("li.sortable a:contains('edit')").click(function(){
alert($(this).parent("li").attr("id"));
})
});

jQuery Selector only on first level not working?

It also fires on the sublist because you don't specify which ul it should start from. The sublist has the same structure, so also qualifies for the selector.

To fix this, add the main lists parent element to the selector, so:

$(document).ready(function(){
$("div#master").on("click", ">ul>li>div", function (){
alert($(this).text());
});
});

Fiddle: http://jsfiddle.net/kQH4x/6/

jquery .each works only on the first element

You can't use the same #id for different elements. Try to rename the rest and you'll get the result you want

Or do this (works without adding any classes - cleaner code)

$('.inner div').each(function(index, domEle){    
$(this).text(index);
});


Related Topics



Leave a reply



Submit