jquery: obtén un conjunto de elementos dom coincidentes

I have a page with div elements everywhere. What's the best way to get the div elements with a custom ID tag. e.g. <div rIndex="34">john</div>, <div rIndex="45">Chris</div>

I'm using this function to look for div elements with rIndex attribute. And I want to put those div elements into an array so I can do further processing.

$("div").each(function(index){

      if($(this).attr("rindex"))   
      {   
     results[index] = $(this);   
      }   
});
alert(results[0])

But the alert message is returning me a function definition, not the element.

preguntado el 27 de agosto de 11 a las 16:08

4 Respuestas

Custom attributes are done like this (w3c) :

<div data-rIndex="34">john</div>

Respondido 27 ago 11, 21:08

You can simply use this jQuery selector:

$('div[rIndex]') 

But, as a side note, can I suggest declaring the divs in this manner instead:

<div data-index="34"></div>

and then using this selector:

$('div[data-index]')

Then your code complies with html standards.

Respondido 27 ago 11, 20:08

Al Tiene atributo selector supports custom attributes:

alert($("div[rIndex]")[0]);

That said, Yoda is right: in this situation, you should prefer the atributos de datos personalizados defined in HTML5:

<div data-rIndex="34">john</div>

alert($("div[data-rIndex]")[0]);

Respondido 27 ago 11, 20:08

HTML

<div data-rIndex="34">john</div>
<div data-rIndex="45">Chris</div>

JavaScript

var results = [];
$("div[data-rIndex]").each(function(index){

  if($(this).data("rindex"))   
  {   
 results[index] = $(this);   
  }   
}); 
alert($(results[0]).html()); //should alert 'john'

I tidied your HTML up a bit, working demo here - http://jsfiddle.net/aerj4/

If you want an array of the divs, you could do this -

var results = [];
$("div[data-rIndex]").each(function(index){

  if($(this).data("rindex"))   
  {   
 results[index] = this;   
  }   
}); 
alert(results[0])//alerts [object HTMLDivElement]

Respondido 27 ago 11, 22:08

Cool but I don't just want the value, I want to store the matched divs into an array. When I do an alert on the result, I don't get divs but anonymous functions - Airnet

Why would you iterate through all the divs in the dom? You could select the divs that have the data-rIndex attribute and just iterate through them. $('div[data-rIndex]') - gislikonrad

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.