SS113
SS113

Reputation: 548

Select DIV ID based on its class

I need to select and use a DIV's ID but I don't know the name of it so I want to search for its class which I know. How would I do that? I can use either plain JS or jQuery, doesn't matter.

I want to be able to get the whole ID based purely on its HA class. A sample div looks like

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

The only way I have been able to get it to work is if I use a regular expression with the first few characters of the ID that I know are not changing (for now) but may in the future so I don't want to risk it.

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

Upvotes: 1

Views: 381

Answers (3)

dakab
dakab

Reputation: 5875

If you know the class, why don’t you just select the element natively using getElementsByClassName?

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

Of course, you can also iterate the HTMLCollection if there’s more items (and not null).

If you have to assert it’s a div, and if you want to get them all, use querySelectorAll instead:

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

Upvotes: 2

AmmarCSE
AmmarCSE

Reputation: 30557

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>

Upvotes: 4

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

If there's only one div with that 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">

Upvotes: 2

Related Questions