1

I'm reading a book on how to create a SPA (single page applications). The author writes, if the IDE is any good then there will be a technique to convert a highlighted section of HTML and converted to a JavaScript string. How can this be done in Visual Studio 2013? An example of how I want the convert to work is below. Also it would be great to toggle back to the html.

HTML

<div class="spa-shell-head">
 <div class="spa-shell-head-logo"></div>
 <div class="spa-shell-head-acct"></div>
 <div class="spa-shell-head-search"></div>
</div>

JAVASCRIPT

var main_html = String()
+ '<div class="spa-shell-head">'
 + '<div class="spa-shell-head-logo"></div>'
 + '<div class="spa-shell-head-acct"></div>'
 + '<div class="spa-shell-head-search"></div>'
+ '</div>';
3
  • 1
    If the programmer is any good then (s)he would never put HTML strings into the code in any form. Commented Aug 26, 2014 at 23:04
  • Paul did you find a solution? @Derek instead of just saying "don't do it", can't you come with something more useful? From my understanding "appending" and similar functions are used quite a lot to add html to places where it wasn't earlier, now that html needs to come from somewhere, so if not from a string, where then? Commented Mar 20, 2015 at 23:26
  • @Logan I've added an answer that explains all that. Commented Jul 13, 2016 at 14:53

1 Answer 1

0

Rather than converting HTML to a JS string, it would be much better to create the elements in JS and put them in the DOM. This would give you much more control, not create such a difficult to maintain/read code, create less problems, and be much faster:

var outerDiv = document.createElement("div");
outerDiv.className = "spa-shell-head";

var innerDivLogo = document.createElement("div");
innerDivLogo.className = "spa-shell-head-logo";

var innerDivAcct = document.createElement("div");
innerDivAcct.className = "spa-shell-head-acct";

var innerDivSearch = document.createElement("div");
innerDivSearch.className = "spa-shell-head-search";

outerDiv.appendChild(innerDivLogo);
outerDiv.appendChild(innerDivAcct);
outerDiv.appendChild(innerDivSearch);
document.body.appendChild(outerDiv);

The above creates the following:

enter image description here

https://jsfiddle.net/yfeLbhe4/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.