如何获取特定类的所有元素的ID?

时间:2014-01-29 13:14:01

标签: javascript jquery css

我有以下代码,想要获取属于特定类的所有元素的id。

code

<ul>
<li><label class="check-lbl"><input id="1" class="translation_box" type="checkbox">اردو</label</li>
    <li><label class="check-lbl"><input id="3" class="translation_box" type="checkbox">Englisg</label> </li>
    <li><label class="check-lbl"><input id="4" class="translation_box" type="checkbox">Hindi</label> </li>
    <li><label class="check-lbl"><input id="5" class="translation_box" type ="checkbox">Bungali</label> </li>
  < /ul>

我在这里说translation_box。任何帮助将不胜感激!

7 个答案:

答案 0 :(得分:5)

您可以使用 .map() 直接从jquery集合中获取ID列表。

var ids = $('.translation_box').map(function(_, x) { return x.id; }).get();

演示: http://jsfiddle.net/ZNxP7/1/

答案 1 :(得分:2)

var allItemsInClass = $(".translation_box");
var arrayIDs = new Array();
$.each(allItemsInClass, function() {
   arrayIDs.push(this.id);
});
alert(arrayIDs.join());

DEMO: http://jsfiddle.net/LG59D/

答案 2 :(得分:1)

使用jQuery

$('.translation_box').each( function () {
 alert($(this).prop('id'));

});

使用JS

var ele = document.getElementsByClassName('translation_box');
for (var i=0; i< ele.length; i++ ) {
  alert(ele[i].id);
}

JSFiddle

答案 3 :(得分:1)

您可以使用jQuery来执行此操作。

$(function(){
  var elements = new Array();
  $('.translation_box').each(function(){
    elements.push($(this).attr("id"))
  });
})

答案 4 :(得分:1)

$('.translation_box').each(function() {   // this loops through all elements with class of tranlation_box
     var x = $(this).attr('id');          // this gets the id of each translation_box and stores it in the variable x
     console.log(x);                      // this logs the id for each one
});

答案 5 :(得分:1)

您可以执行以下操作:

 function getIds() {
   var elements = document.getElementsByClassName("translation_box");

   for(var i=0; i<elements.length; i++) {
    console.log(elements[i].getAttribute("id"));
   }

 }

答案 6 :(得分:1)

  

它返回数组中的所有id

var idArray = [];

$('.translation_box').each(function() {
               var id = $(this).attr('id');
               idArray.push(id);
            });
alert(idArray)
相关问题