开发者

jquery - get a set of matched dom elements

开发者 https://www.devze.com 2023-03-30 23:58 出处:网络
I have a page with div elements everywhere. What\'s the best way to get the div elements with a custom ID tag.

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 开发者_JS百科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.


Custom attributes are done like this (w3c) :

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


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.


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]);


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消