0

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
}       
2
  • Look up the array.slice(...) function Commented Jan 14, 2013 at 18:42
  • ok i am checking array.slice() Commented Jan 14, 2013 at 18:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It's still the fifth element of the array, it only resides at index 4. Unless you're from the "zeroth element" school of thought? :)
question is or any particular div element
this gives me id of text box. thats fine. i want id of the div
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.