Reputation: 11175
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?
Upvotes: 49
Views: 133179
Reputation: 21
Unless "<br>
" is passed as innerHTML to any element, it will not be rendered as an HTML tag. So we can use a dummy '<span>
' element and keep '<br>
' as its innerHTML so that it will be rendered as expected.
br = document.createElement("span");
br.innerHTML = "<br/>
";
document.body.appendChild(br);
Upvotes: 2
Reputation: 3136
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"> </span>
This text will go down every time you click on add button
Upvotes: 18
Reputation: 147413
This question has nothing whatever to do with markup. The argument passed to createElement is an element name, it is not a fragment of markup or anything else, it isn't XML, or HTML, or XHTML, or SGML or any form of markup.
The createElement method returns a DOM object, there is no markup and never was.
Note that the markup passed to the browser is used to create a document object, from that point onward, the markup is irrelevant.
Upvotes: 4
Reputation: 10499
In reality, your code will still validate if your JavaScript doesn't exactly validate, because the validator only parses the processed HTML code, not the dynamic code created by JavaScript. If you cared, you could also use an innerHTML
trick, or a document.createTextNode('<br />');
if you wanted to force the XHTML version, but it is not recommended. document.createElement('br');
works perfectly fine.
Upvotes: 3
Reputation: 25014
The first method does not need to pass XHTML standards - you're confusing markup with manipulating the DOM.
Upvotes: 15
Reputation: 169018
The first option will work and has nothing to do with XHTML since the DOM operations are performed after parsing of the document, and therefore there is no XHTML/HTML standard to be compliant to at that point. As long as you are not trying to output the HTML to a string, this approach will work just fine.
Upvotes: 9