What Is the Correct Way to Write HTML Using JavaScript

What is the correct way to write HTML using Javascript?

document.write() will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body> tag and the DOM is ready, you can't use document.write() anymore.

I wouldn't say using document.write() is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write() to accomplish the task. Look at how Google analytics gets injected into most websites.

After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id="node-id"></div>):

  1. Using innerHTML on a node:

    var node = document.getElementById('node-id');
    node.innerHTML('<p>some dynamic html</p>');
  2. Using DOM methods:

    var node = document.getElementById('node-id');
    var newNode = document.createElement('p');
    newNode.appendChild(document.createTextNode('some dynamic html'));
    node.appendChild(newNode);

Using the DOM API methods might be the purist way to do stuff, but innerHTML has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.

Note: The <script> will have to be inside your <body> tag for this to work.

Good practices for writing HTML in Javascript

http://ejohn.org/blog/javascript-micro-templating/ is a devilishly brilliant hack for this. End result is very clean.

Write HTML to screen with Javascript function

Have your function return the table as a string.

function createTable()
{
var table = "<table>";

table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";

return table;

}

Assuming you don't want to overwrite the body completely create a div have it styled the way you want and just add the table content there.

<body>
<div id="table"></div>
<script>
var table=createTable();
document.getElementById("table").innerHTML=table;
</script>
</body>

How do I use just JavaScript to create HTML code?

Using JavaScript to create HTML:

Creating HTML elements:
Each HTML element must first be specifically created.

There are a variety of ways to do this. The most commonly used are:

  • Use document.createElement() to create the element.

    var myDiv = document.createElement("div");
    myDiv will be a reference to the element you just created. The element will not yet be part of the DOM. If you want it to be displayed, you will need to add it to the DOM.
  • Assign an HTML string to the innerHTML property of another element.

    containingElement.innerHTML = "<div id="divA"><div id="divB">Some Text"</div></div>";
    There are a variety of potential issues with directly adding HTML text to the DOM. In particular, there are security issues if any part of the HTML text you are adding is not derived from strings hard coded in your program.

    Depending on what you are assigning, there can be performance issues with repeatedly changing large parts of the DOM by assigning to innerHTML.
  • Assign text to the textContent property of another element. This will remove any other children and create a single text node as the only child for the element.

    elementToHaveText.textContent = "The text I want in this element."
  • Use cloneNode() to create a copy of a node, or a node and all its children.

    var theCopy = nodeToCopy.cloneNode() //thecopy will be a copy of nodeToCopy.
    var theCopy = nodeToCopy.cloneNode(true) //Create a copy of nodeToCopy and all children.
  • Use insertAdjacentHTML() to create elements and insert them into the DOM using HTML text at the same time. This method provides more control over inserting the elements generated from HTML text. In many/some cases it will be faster than other types of node generation and insertion. The HTML is inserted in relation to a reference element. You can insert the HTML, before, as children (either at the beginning or end), or after the reference element.

    refEl.insertAdjacentHTML('afterend',"<div id="A"><div id="B">Some Text"</div></div>");
    This method has the same security concerns and assigning to innerHTML regarding direct conversion HTML text that is not hard coded in your program.

There are additional ways to create HTML elements. You will want to look at the documentation for documents, nodes and elements.

Adding elements to the DOM:
In order for an HTML element to be visible it must be added to the DOM. There are multiple ways to add an element to the DOM. The most commonly used are:

  • Use a methodology that both creates the nodes and inserts them into the DOM at the same time. You can do so with:

    • Assign an HTML string to the innerHTML property of another element.
    • Use insertAdjacentHTML() to create and insert elements into the DOM using HTML text.
  • Use appendChild() to add a child to the end of an element's list of children.

    element.appendChild(aChild);
  • Use insertBefore() to add a child to a parent prior to another child of that parent.

    parentNode.insertBefore(aChild, referenceChild);
  • Use replaceChild() to replace a child of a parent node.

    parentNode.replaceChild(aChild, oldChild);

As with creating elements, there are additional ways to add elements to the DOM. You will want to look at the documentation for documents, nodes and elements.

You can not use the same element in the DOM multiple times. If you try to do so, the element which you are trying to add in a second place will be moved from its current place in the DOM to the place where you are inserting it. This is the normal way to move an element rather than explicitly removing it and then re-adding it in another location.

If you want to add elements which have children, you either have to create them all at one time using one of the methodologies that creates and inserts HTML text, or you need to have references to the nodes you create in order to use them when adding children later. It is significantly more efficient to have a variable which is a reference to the parent node you have created rather than having to search the DOM for that node in order to add children.

Regarding your code:

  • You are passing a string to appendChild() when you should be passing an element.
  • You are using document.getElementById() to try to get references to elements which you have just created.

    • None of your elements have IDs in the HTML. You appear to be adding IDs just so you can use document.getElementById() to find the elements you created.
    • If you need a reference to an element you created, you should be keeping the reference you get from creating the element. It is bad practice to perform a bunch of extra processing (searching for an element) which is completely unneeded.
    • You should never need to perform a call to document.getElementById() to get a reference to an element that you have created in the same function in which you need the reference.
  • You are using createTextNode().

    • This is a method of document, not element.
    • For your use, setting the only child node to be a single text child node, it is more efficient to just assign to Element.textContent.
  • You have created the variables makeDiv, makeHead, and makeBTN which you appear to be trying to use multiple times as a different element each time you are referring to the variable. It does not work the way you have coded it. As written, there is only one element of each type created. You can not use the same element in multiple locations in the DOM.

    • Each element must be specifically created. While there are other ways to create separate elements (e.g. cloneNode()), the most common is document.createElement().
  • You have written way too much linear code. Your elements are very similar. You should code this such that creating them is modular.

From your question, it is unclear to me if you are attempting to create the entirety of the HTML code you have provided, or if you are trying to create everything from the <div> with class="row" and add it to the DOM within a <div> with class="container". I have assumed that you are attempting to create the entirety of the HTML.

I have also assumed that you want the HTML you have listed in the question without the additional attributes which are in your JavaScript.

Here is some code that creates the HTML you are looking for:

function createDesiredHtmlElements() {
function createDiv(theClass) {
var div = document.createElement("div");
if(typeof theClass === "string") {
div.className = theClass;
}
return div;
}
function createButton(text,theClass,type) {
var button = document.createElement("button");
type = (typeof type === "undefined") ? "button" : type;
theClass = (typeof theClass === "undefined") ? "btn btn-default" : theClass;
button.setAttribute("type",type);
button.className = theClass;
button.textContent = text;
return button;
}
function createButtonGroupDiv(buttonsText,divClass) {
buttonsText = (typeof buttonsText === "string") ? [buttonsText] : buttonsText;
divClass = (typeof divClass === "undefined") ? "btn-group" : divClass;
var div = createDiv(divClass);
if(Array.isArray(buttonsText)) {
buttonsText.forEach(function(buttonText) {
div.appendChild(createButton(buttonText));
});
}
return div;
}
//Actually create the HTML:
var mainDiv = createDiv("container");
var rowDiv = mainDiv.appendChild(createDiv("row"));
var colDiv = rowDiv.appendChild(createDiv("col-md-12"));
colDiv.appendChild(document.createElement("h3")).textContent = "Nothing clicked yet!";
colDiv.appendChild(createButton("Star","btn btn-default btn-lg"));
colDiv.appendChild(document.createElement("hr"));
var midDiv = colDiv.appendChild(createDiv());
midDiv.appendChild(createButtonGroupDiv(["1","2","3","4"]));
midDiv.appendChild(createButtonGroupDiv(["5","6","7"]));
midDiv.appendChild(createButtonGroupDiv("8"));
colDiv.appendChild(document.createElement("hr"));
var midDiv2 = colDiv.appendChild(createDiv());
midDiv2.appendChild(createButtonGroupDiv(["Left","Middle","Right"]
,"btn-group btn-group-lg"));
return mainDiv;
}

If you then do the following:

var theDiv = createDesiredHtmlElements();
console.log(theDiv.outerHTML);

You will see the HTML:

<div class="container">
<div class="row">
<div class="col-md-12">
<h3>Nothing clicked yet!</h3>
<button class="btn btn-default btn-lg" type="button">Star</button>
<hr>
<div>
<div class="btn-group">
<button class="btn btn-default" type="button">1</button>
<button class="btn btn-default" type="button">2</button>
<button class="btn btn-default" type="button">3</button>
<button class="btn btn-default" type="button">4</button>
</div>
<div class="btn-group">
<button class="btn btn-default" type="button">5</button>
<button class="btn btn-default" type="button">6</button>
<button class="btn btn-default" type="button">7</button>
</div>
<div class="btn-group">
<button class="btn btn-default" type="button">8</button>
</div>
</div>
<hr>
<div>
<div class="btn-group btn-group-lg">
<button class="btn btn-default" type="button">Left</button>
<button class="btn btn-default" type="button">Middle</button>
<button class="btn btn-default" type="button">Right</button>
</div>
</div>
</div>
</div>
</div>

Note that the code above does not actually put the created HTML into the DOM. You have not specified what you want done with the HTML once it is created.

best way to inject html using javascript

Shove the entire thing into a JS variable:

var html = '<a href="#" id="playButton">Play</a>';
html += '<a href="javascript: void(0)" id="muteUnmute">Mute</a>';
html += '<div id="progressBarOuter"><div id="bytesLoaded"></div><div id="progressBar"></div></div>';
html += '<div id="currentTime">0:00</div>';
html += '<div id="totalTime">0:00</div>';

Then:

document.getElementById("parentElement").innerHTML = html;

if you want theN:

document.getElementById("totalTime").innerHTML = "5:00";

Javascript document.write('HTML CODE HERE') and using a var grabbed by flash

First, JavaScript doesn't allow multiline strings, so right-off-the-bat your document.write is going to throw a syntax error. You have at least a couple of ways to go about it. You could just remove the line breaks, making the entire string a single line...

var lines = '<div id="jwplayer"><center>...</center></div>';
document.write(lines);

...but that tends to not be so readable. Or you can escape the line breaks with backslashes...

var lines = '<div id="jwplayer">\
<center>\
...\
</center>\
</div>';
document.write(lines);

...which is more readable, but probably kind of brittle -- any trailing whitespace after the backslashes will break it without being apparent. Next you could concatenate the string a line at a time...

var lines = '<div id="jwplayer">';
lines += '<center>';
lines += '...';
lines += '</center>';
lines += '</div>';
document.write(lines);

...which I think somewhat mitigates the readability issue of the first method and the brittleness issue of the second. Lastly, you could create an array of strings and join them...

var lines = [
'<div id="jwplayer">',
'<center>',
'...',
'</center>',
'</div>'].join(' ');
document.write(lines);

...which has the [entirely subjective] advantage of eliminating the repetetive lines += .... In any case, that's by no means an exhaustive list of approaches, it mostly boils down to using whatever you're most comfortable with.

Next, your string is, quite frankly, a huge mish-mash of conflicting single- and double-quotes. If you need to include the same kind of quotes in your string as you're using to enclose the string, then you need to escape them:

var lines = "<div id=\"jwplayer\">";
lines += '<div id=\'mediaplayer\'></div>';

Obviously(?) you'd want to keep the escapes to a minimum, and since you're creating a string(s) of html, you'd probably want to enclose those with single-quotes and use double-quotes for the attribute values. But again, it's whatever style makes the most sense to you.

And finally, both of the above issues are what are causing the streamName parameter passed into the function not to work, since you were already running into numerous errors long before you got to that line. If you keep the string issues straight, then

lines += "'file': 'onSaveOk(" + streamName + ")'";

should work just how you want it to.

Note: I'm foregoing the obligatory warnings about a) using document.write() and b) using <center> tags, but you should take some time to do a little research into both of those issues; I will just say that 1998 called and said, "That's cool, I didn't want those back anyhow".

How can I create HTML tags using Javascript?

here is the javascript you are looking for.
a small example of creating elements via js. by reading this. you should be able to accomplish what you want.

const root = document.querySelector('body') //or target div
const div = document.createElement('div');
div.innerHTML = "text for div";
const img = document.createElement('img');
img.setAttribute('src', 'urlString');
div.setAttribute('id','box');

div.appendChild(img);
root.appendChild(div);



Related Topics



Leave a reply



Submit