airnet
airnet

Reputation: 2673

jquery - get a set of matched dom elements

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.

Upvotes: 1

Views: 334

Answers (4)

ipr101
ipr101

Reputation: 24236

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]

Upvotes: 0

yoda
yoda

Reputation: 10981

Custom attributes are done like this (w3c) :

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

Upvotes: 3

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263147

The Has Attribute selector supports custom attributes:

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

That said, Yoda is right: in this situation, you should prefer the custom data attributes defined in HTML5:

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

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

Upvotes: 1

gislikonrad
gislikonrad

Reputation: 3591

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.

Upvotes: 1

Related Questions