GustX
GustX

Reputation: 45

Best way of appending two <br> before making a new html element with vanilla javascript?

I have a button when clicked creates a input and I want it to be separated by a space ontop and I noticed 1 <br> just makes it go to a new line so I wanted to add two but when I do this

function createInput(){

var br = document.createElement("br");
  var input = document.createElement("input");
  input.type = "file";

  document.body.appendChild(br);
  document.body.appendChild(br);
  document.body.appendChild(input);


}

It only shows up with one line down.

Upvotes: 0

Views: 62

Answers (2)

guest271314
guest271314

Reputation: 1

You can use Element.insertAdjacentHTML()

document.body.insertAdjacentHTML("beforeend", "<br><br><input type='file'>")

Upvotes: 1

Tibrogargan
Tibrogargan

Reputation: 4603

From the MDN documentation of appendChild:

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

Because you are appending the same element twice, the second time all it's doing is moving the element from it's current position (the end of the document) to the end of the document. i.e. It's not doing anything. You need to create a 2nd br:

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

Or better still, as @torazaburo suggests, use CSS properties for your layout (But one thing at a time, hey?)

Upvotes: 2

Related Questions