Select DIV ID based on your class

I need to select and use a DIV ID, but I don't know its name, so I want to find its class that I know. How should I do it? I can use either plain JS or jQuery, it doesn't matter.

I want the whole id to be class based only HA

. The sample div looks like

<div class="HA" id="k2348382383838382133">

      

The only way I was able to get it to work is by using a regex with the first few id characters, which I know don't change (yet) but may in the future, so I can't wanna risk it.

var selectDivID = $('div[id^="k23"]');

      

+1


source to share


3 answers


If you know the class, why don't you just select the element initially using getElementsByClassName

?

var id = document.getElementsByClassName('HA').item(0).id;

      

Of course, you can also repeat HTMLCollection

if theres more items (not null

).



If you need to approve it div

, and if you want to get them all, instead of querySelectorAll

:

var IDs = [];
Array.prototype.forEach.call(document.querySelectorAll('div.HA'),
                             function(item){ IDs.push(item.id) });
console.log(IDs);

      

+2


source


Use attr ()

$('.HA').each(function(){
    var selectDivID = $(this).attr('id'); // or this.id
});

      



$('.HA').each(function() {
  var selectDivID = $(this).attr('id');
  console.log(selectDivID);
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="HA" id="k2348382383838382133"></div>
<div class="HA" id="k2344444444444444444"></div>
<div class="HA" id="k234543544545454454"></div>
<div class="HA" id="k2346787878778787878"></div>
      

Run code


+4


source


If there is only one div

with this class, you can simply do this:

var selectDivID = $('div.HA')[0].id;
console.log(selectDivID);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="HA" id="k2348382383838382133">
      

Run code


+2


source







All Articles