When is it acceptable to output HTML from Javascript?

I read part of the 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 webapp this piece of code is used and displayed on the page.

output_html(html);

I assume that, given this specific example of a hidden context menu, the developer probably did not want to repeat it himself.

Is such a practice encouraged or should it be seen as the wrong approach?

+5
source share
3 answers

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

, HTML, script, PHP. , , , PHP , HTML .

+2

HTML , CSS : , .

, , , , .


: :

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);

, , , Javascript HTML; HTML ! "webapp".

+2

... , "html".

- , XHTML. , HTML CSS, / .

CSS, JavaScript - , JS , , . , manu, , , , , , , , .

In your case, since there is no "href" for anchors, I assume that these elements only work when JavaScript is enabled, so I really don't see a problem with inserting it through JS. (as well as for inserting HTML and executing it by element ... if it is HTML, not XHTML, I have no problem inserting a string, since it is easier for me to support it ... and if it is actually an HTML file, I say there even more reason to keep it as an HTML string)

0
source

All Articles