简体   繁体   中英

javascript: Extract elements from array

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
}       

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM