Attempting to add a button but getting “[object HTMLInputElement]” instead of the button

痴心易碎 提交于 2020-01-26 04:35:06

问题


I'm trying to build buttons dynamically in a for loop where each iteration builds a button. I've done this before no problem and copied this code from an old project. Now I get [object HTMLInputElement] posted to the DOM instead of my button.

Any advice? Thanks.

What I have so far:

var element = document.createElement("input");
element.className = 'appointmentClass'
element.id = countAppointments;
element.type = 'button';
element.name = 'name';
element.value = 'remove';
element.onclick = function () {
        alert('removed appointment '+ this.id)
//      addShow(this.id);
};

回答1:


When you do

tableRow.append("<td>" + element + "</td>"); 

You are causing the browser engine to call toString() on the DOM node which results in what you are seeing. You need to create a td element and append the button to the TD element. and than append the td to the tr.

pure JS

var td = document.createElement("td");
td.appendChild(element);
tableRow.appendChild(td);  //or     tableRow.append(td);

or with jQuery

var td = $("<td></td>");
td.append(element);
tableRow.append("td"); 



回答2:


you just need to append the button to the body using parentElement.appendChild(element)

var 
  element = document.createElement("input");
element.className = 'appointmentClass'
element.id = 'countAppointments';
element.type = 'button';
element.name = 'name';
element.value = 'remove';
element.onclick = function (){
  alert('removed appointment '+ this.id)
  //  addShow(this.id);
}

document.body.appendChild( element );



回答3:


You are not appending DOM element anywhere. You can use parentNode.appendChild method which accepts argument as a node

Try this:

var parent = document.getElementById('conteiner');
for (var i = 0; i < 10; i++) {
  var
    element = document.createElement("input");
  element.className = 'appointmentClass'
  element.id = 'countAppointments' + i;
  element.type = 'button';
  element.name = 'name';
  element.value = 'remove';
  element.onclick = function() {
    alert(this.id);
    this.parentNode.removeChild(this);
  };
  parent.appendChild(element);
}
<div id="conteiner"></div>

Fiddle here




回答4:


you can try Jquery append method like:

$(".container").append("<input type="button" value="XXXX" name="XXXX" id="XXXXX">");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



回答5:


It turns out I can't append with for this input element. Removing this and just appending 'element' as I was previously works.



来源:https://stackoverflow.com/questions/34647170/attempting-to-add-a-button-but-getting-object-htmlinputelement-instead-of-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!