How to insert a line break with javascript?

左心房为你撑大大i 提交于 2019-12-01 03:27:10

You should create new <br> tag each time when you will append it, something like

linebreak = document.createElement("br");
queryForm.appendChild(linebreak);

DEMO

The problem with your code is you're inserting the same element over and over again.

Here's an analogy: Imagine you have several children lined up in a row. Yes you can attempt to move one of them after each of the other children, however, at the end of the day you still only have one of that child. He's going to end up at the end of the row.

Solution: Create the line break element each time you need to insert it.

Also, here's an obligatory plug for jQuery: http://www.jquery.com

You should try to append each time a new node, and not the same one that was previously created, i.e:

queryForm.appendChild(document.createElement("br"));

EDIT: the explanation is here on the documentation

Node.appendChild Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild

Protip: Append your inputs to your labels. That way a user can click the label to get focus on the input.

This has the additional perk that you can simply apply the CSS display:block to your labels and have them on separate lines!

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