Reputation: 31
I have no idea whether this should be done or not.
Here is my problem:
I created an function which creates and stores 10 div elemets(with unique IDs).
I want to make another function which would take an array as its parameter and alert the ID of the 5th div(or any particular div element).
Please help
function createText(){
var combo = [];
for( i =0; i<=5 ; i++) {
var newText = document.createElement("input");
newText.type = "text";
newText.id = "text"+i;
newText.style.width ="20px";
newText.style.height ="20px";
var newDiv = document.createElement("div");
newDiv.type = "div";
newDiv.id = "div"+i;
newDiv.style.backgroundColor ="red";
newDiv.style.cssFloat = "left";
document.getElementById("tryingin").appendChild(newDiv.cloneNode());
combo.push(document.getElementById("div"+i).appendChild(newText.cloneNode()));
}
alert(combo);
}
function alert(arr) {
//now I want to alert the id of the div(or textbox) here
}
Upvotes: 0
Views: 573
Reputation: 3635
Your function is wrong.
combo.push(document.getElementById("div"+i).appendChild(newText.cloneNode()));
Here you add the input to the div and then you add input to the array. The appendChild method returns a reference to the added node.
you need to be doing it in two lines:
document.getElementById("div"+i).appendChild(newText.cloneNode());
combo.push(document.getElementById("div"+i));
Then you need a function like so:
function aklertDivbyIndex(theDivs, index){
return alert(theDivs[index].id);
}
Upvotes: 0
Reputation: 1443
Assuming you have an array of divs all with unique ids, a function would look something like this:
function alertFifth(listOfDivs) {
alert(listOfDivs[4].id);
}
JavaScript allows for access into arrays by index starting at 0 (as with most modern languages). Note that the fifth element is considered the 4th in CS terms.
Upvotes: 1