繁体   English   中英

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

[英]How to get the ids of all elements of a particular class?

我有以下代码,并希望获取属于特定类的所有元素的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 任何帮助将不胜感激!

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

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

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

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

演示: http : //jsfiddle.net/LG59D/

使用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

您可以使用jQuery来做到这一点。

$(function(){
  var elements = new Array();
  $('.translation_box').each(function(){
    elements.push($(this).attr("id"))
  });
})
$('.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
});

您可以按照以下方式进行操作:

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

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

 }

它返回数组中的所有id

var idArray = [];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM