对多个对象使用类似getElementById的东西?

时间:2014-12-23 19:09:11

标签: javascript html

我目前正在使用document.getElementById(“ID”)方法从输入区域获取值并将其粘贴到div上。

这工作正常,但我想将这些结果粘贴到两个不同的div中,这意味着我不能使用getElementById方法。

我尝试使用getElementsByName但由于某种原因无效。

Here's my JSFiddle with the working code using GetById。我想要的是让它输出两个输出区域中的元素而不仅仅是第一个元素。

var counter1 = 0; //Prevents user from creating multiple nodes on submit
var limit1 = 8; //Amount of nodes that can be created per input field
document.getElementById('textInput1').addEventListener('keypress', function (e) {
    if (e.which === 13) {
        e.stopPropagation();
        e.preventDefault();
        createNode1();
    }
});
//CREATES FORMATTED NODE FROM INPUT VALUE
function createNode1(){
    if (counter1 == limit1)  {
    //Do nothing
    }
else {
    var input = document.getElementById('textInput1').value; //Retrieves input
    var newText = document.createElement("li"); //Creates the HTML node
    newText.innerHTML = input; //Sets the node's value to whatever is in the input
    document.getElementById("Form1").appendChild(newText); //Adds the node to the div
    document.getElementById('textInput1').value=""; //Clears text field after submit
    counter1++;
    }
}
//CLEARS THE FORM IF YOU MADE A MISTAKE
function deleteNode1(){
    var node = document.getElementById('Form1');
    while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
    counter1=0;
    }
}

1 个答案:

答案 0 :(得分:1)

使用ID

试试这个...使用两个电话......

Output1:
<div id="Form1"></div>
<p>
Output2:
<div id="Form2"></div>

......和......

var newText1 = document.createElement("li"); //Creates the HTML node
var newText2 = document.createElement("li"); //Creates the HTML node
newText1.innerHTML = input; //Sets the node's value to whatever is in the input
document.getElementById("Form1").appendChild(newText1); //Adds the node to the div
newText2.innerHTML = input; //Sets the node's value to whatever is in the input
document.getElementById("Form2").appendChild(newText2); //Adds the node to the div

基本上,我已经用值创建了两个li元素。然后将其发布到ID的Form1Form2

使用CLASS

如果您使用过类,则可以遍历getElementsByClassName es。

尝试......

Output1:
<div id="Form1" class='formtype'></div>
<p>
Output2:
<div id="Form2" class='formtype'></div>

var classlist = document.getElementsByClassName("formtype");
for (var i=0; i<classlist.length; i++) {
  var newText = document.createElement("li"); //Creates the HTML node
  newText.innerHTML = input; //Sets the node's value to whatever is in the input
  classlist[i].appendChild(newText); //Adds the node to the div
}