Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a <br /> with javascript createElement?

I need to create a <br /> tag dynamically with javascript.

var br = document.createElement('br'); 

And

var br = document.createElement('<br />'); 

doesn't work

The first option urrently creates a <br> tag on the page which doesn't pass XHTML standards, is there anyway around this?

like image 238
Phil Avatar asked Jan 11 '11 04:01

Phil


People also ask

What is br /> in JavaScript?

To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.

What does createElement () do?

createElement() In an HTML document, the document. createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.

How do you add a br tag dynamically?

To add a BR in JavaScript the method createElement() is used. We can use it within our document and append the line break to the DOM like so: const testElement = document. querySelector('div'); const lineBreak = document.


2 Answers

The first method does not need to pass XHTML standards - you're confusing markup with manipulating the DOM.

like image 51
jball Avatar answered Oct 06 '22 00:10

jball


A Simple Script of HTML and JavaScript to add br tag dynamically in the page.

 <SCRIPT language="javascript">     function add() {       //Create an input type dynamically.         var br = document.createElement("br");         var foo = document.getElementById("fooBar");         foo.appendChild(br);     }      </SCRIPT>      <INPUT type="button" value="Add" onclick="add()"/>     <span id="fooBar">&nbsp;</span>      This text will go down every time you click on add button 
like image 36
Nagri Avatar answered Oct 05 '22 23:10

Nagri