Select several ids with javascript

1

I was doing an element search on a page. I try to catch all the elements with the same id, and I only get the first one with both JS and jQuery. I know that if I would do it with classes, I could do it without problems, but I still have the doubt that could be done with ids.

Greetings.

    
asked by Pablo Pérez-Aradros 07.06.2016 в 12:31
source

4 answers

1

Although the best thing -by convention- is to use unique ids, from the context of an XML document (or SGML in its absence), the id is just one more attribute of the element. Therefore the attribute selector is a valid alternative in both javascript and jQuery.

The attribute selector syntax is [id=valor]

Examples:

console.log(document.querySelectorAll('[id=a]'));
console.log($('[id=a]'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a"></div>
<div id="a"></div>
<div id="a"></div>
<div id="a"></div>
<div id="a"></div>
<div id="a"></div>
    
answered by 08.06.2016 / 02:05
source
2

You have to bear in mind, that a label id and a label class are not the same, and you should know when to use one label or another.

id is unique

  • Each element can have only a id associated
  • Each page can only have one element with that id

class is NOT unique

  • You can use the same class in multiple elements
  • You can use multiple class on the same element

Example:

<div id="left-box" class="main-box dark"></div>
<div id="right-box" class="main-box light"></div>

Although it may be confusing at first, it is easy to remember, you should only think that class equals one type of element, while id is the name given.

    
answered by 07.06.2016 в 12:56
2

Although as you commented, it is not advisable to have 2 or more elements with the same id, but if you had it, you could access all the elements via querySelectorAll ... that is:

document.querySelectorAll("#id");

The querySelectorAll will give you an array with the records found. Let's see an example:

HTML

<input type="text" id="a" > < input type="text" id="a" > < input type="text" id="a" >

JS

var a = document.querySelectorAll("#a"); console.log(a);
    
answered by 07.06.2016 в 17:12
1

The problem is that the HTML specifications require that the ID is unique on each page, but if you really need to do it, try iterating:

function porQueHacesEsto() {
    var n = document.getElementById("id-no-unica");
    var a = [];
    var i;
    while(n) {
        a.push(n);
        n.id = "id-diferente";
        n = document.getElementById("id-no-unica");
    }

    for(i = 0;i < a.length; ++i) {
        a[i].id = "id-no-unica";      
    }
    return a;
}

This answer is extracted from other answers from stackoverflow.com

    
answered by 07.06.2016 в 12:55