dynamically added text id, getElementById

2019-08-10 02:36发布

问题:

I create text box dynamically and assign its ID dynamically. in javascript if I call getElementById the alert fails, just nothing happens.

<% for(int i=0; i<lines.length;i++) {
  if(lines[i].contains(" ")) { %>
    <input type=text name='key1<%=i%>' id="idkey<%=i%>" value ="<%=abc%>"/>
                          <%
  }
} %>

Javascript :

for(j=0; j<len; j++){
  var lblElement = getElementById("idkey"+j);
  alert(lblElement);
}

回答1:

you forgot the global name document for use getElementById

document.getElementById('idkey'+j)



回答2:

You're missing document before getElementById:

for(j=0; j<lines.length; j++){
    var lblElementID = document.getElementById('idkey'+j);
    console.log(lblElementID);
}


回答3:

You forget to use the document global namespace

The correct way to access the getElementById is the following

document.getElementById('idkey')