简体   繁体   中英

how to get current htmlSelectElements id

hi i have been trying to get the id of the current element that I am looping through but I am not sure why this doesnt work any help is greatly appreciated!

code:

var arr = document.getElementsByClassName("myclass");
for (i = 0; i < arr.length; i++) {
    var key = "";
    var value = "";
    if (arr[i].nodeName == "INPUT" || arr[i].nodeName == "TEXTAREA") {
        key = arr[i].name;
        value = arr[i].value;
    }
    else if (arr[i].nodeName == "SELECT" && arr[i].attr('id') == "multiple") {
        alert("worked");
        key = arr[i].name;
        value = "multi";
    }
    else if (arr[i].nodeName == "SELECT" && arr[i].attr('id') != "multiple") {
        alert("ddint work");
        key = arr[i].name;
        value = "not multi";
    }
}​

I am not able to get the id from my arr[i] position even though it is an element.

arr[i] is an element, not a jQuery object. you can access the id property directly with arr[i].id

var arr = document.getElementsByClassName("myclass");
for (i = 0; i < arr.length; i++) {
    var key = "";
    var value = "";
    if (arr[i].nodeName == "INPUT" || arr[i].nodeName == "TEXTAREA") {
        value = arr[i].value;
    }
    else if (arr[i].nodeName == "SELECT" && arr[i].id == "multiple") {
        alert("worked");
        value = "multi";
    }
    else if (arr[i].nodeName == "SELECT" && arr[i].id != "multiple") {
        alert("ddint work");
        value = "not multi";
    }
    key = arr[i].name;
}​

.attr("id") is a jquery function. The javascript equivalent is .id

Also you can move the key variable assignment outside of the if statements because you assign it regardless of the if statements.

using .id on a node is not recommended. use .getAttribute.

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