Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when it's acceptable to output HTML code from Javascript?

I read a piece of Javascript code, where the programmer added something similar to this:

html = " 
        <div class='hidden-context-menu'>
          <ul><li><a class='select-all'>All</a></li>
              <li><a class='select-none'>None</a></li>
               ...
               ...
               ...
          </ul>
        </div>
 "

and then, in some other parts of the webapp, this piece of code is used and rendered in the page.

output_html(html);

I assume, considering this specific example of a hidden context menu, that maybe the developer did't want to repeat himself..

Is this kind of practice encouraged or it has to be considered a wrong approach?

like image 622
Rdpi Avatar asked Oct 08 '22 11:10

Rdpi


2 Answers

I would say that relying on Javascript to generate your HTML is probably a bad idea. What if the user has Javascript turned off in their browser?

I think that it is more common to find HTML generated by a server-side script, like PHP. The resulting page that the client receives is the same as it would be if PHP wasn't used, and the developer just typed out the HTML repeatedly.

like image 172
Travesty3 Avatar answered Oct 12 '22 11:10

Travesty3


Outputting HTML in this fashion can lead to a lot of headaches in the future, for the same reason CSS should be external: harder to find, mixes with unrelated code, and often results in needless repetition.

If the framework you're told to use requires it, or if a former developer riddled the code with it, there really isn't too much that can be done.


Edit: the following code will perform the same function, and is easier to manipulate in the future:

var div = document.createElement("div");
div.className = "hidden-context-menu";

var ul = document.createElement("ul");

var li = document.createElement("li");
var a = document.createElement("a");
a.className = "select-all";
li.appendChild(a);
ul.appendChild(li);

var li = document.createElement("li");
var a = document.createElement("a");
a.className = "select-none";
li.appendChild(a);
ul.appendChild(li);

div.appendChild(ul);

And by the way, as the above poster said, Javascript should not be the only mechanism for outputting HTML; the HTML page should be responsible for that! It's fine in 'webappy' applications, however.

like image 34
Jeffrey Sweeney Avatar answered Oct 12 '22 11:10

Jeffrey Sweeney