function storeid(){
var className = document.getElementsByClassName('Jicon');
var classnameCount = className.length;
var IdStore = new Array();
for(var j = 0; j < classnameCount; j++){
IdStore = classnameCount.id[j];
}
}
My intention is to get the id of all elements with a specific class name and store them in array.
Demo
function storeid(){
var className = document.getElementsByClassName('Jicon');
var classnameCount = className.length;
var IdStore = new Array();
for(var j = 0; j < classnameCount; j++){
IdStore = classnameCount.id[j];
}
}
My intention is to get the id of all elements with a specific class name and store them in array.
Demo
Share Improve this question edited Oct 15, 2015 at 12:29 Wolf 10.3k8 gold badges68 silver badges112 bronze badges asked Oct 15, 2015 at 11:50 HacktorHacktor 833 silver badges10 bronze badges5 Answers
Reset to default 3You will get all the ids in IdStore array.
function storeid(){
var className = document.getElementsByClassName('Jicon');
var classnameCount = className.length;
var IdStore = new Array();
for(var j = 0; j < classnameCount; j++){
debugger;
IdStore.push(className[j].id);
}
alert(IdStore.length);
}
storeid();
<div class="Jicon" id="displayImage1">image1</div>
<div class="Jicon" id="displayImage2">image2</div>
<div class="Jicon" id="displayImage3">image3</div>
<div class="Jicon" id="displayImage4">image4</div>
I prefer querySelectorAll for this kind of things, since getElementsByClassName returns a live list, which could mess up other logic if you add/remove elements with that class.
var ids = Array.prototype.slice.call(document.querySelectorAll('.Jicon')).map(function ( element ) {
return element.id;
});
You need few changes like following:
You must use className
as it's actual array of elements which is returned by your query getElementsByClassName()
You must use .push()
to add item into the array
for(var j = 0; j < classnameCount; j++){
IdStore.push(className[j].id); // use className instead of classnameCount
}
Demo
function storeid(){
var className = document.getElementsByClassName('Jicon');
return className.map(function(cur){
return cur.id
});
}
document.write( JSON.stringify(storeid()) )
<div class="Jicon" id="displayImage1">image1</div>
<div class="Jicon" id="displayImage2">image2</div>
<div class="Jicon" id="displayImage3">image3</div>
<div class="Jicon" id="displayImage4">image4</div>
function storeid(){
var className = document.getElementsByClassName('Jicon');
var classnameCount = className.length;
var IdStore = new Array();
for(var j = 0; j < classnameCount; j++){
IdStore[j] = className[j].id;
}
alert(IdStore.length);
}
here goes your code. Voila!! NOTE: remove the alert in code.