最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Generating HTML tags through vanilla javascript - Stack Overflow

programmeradmin3浏览0评论

Some sites use the following JavaScript line to build the site:

document.write('<link rel="stylesheet" type="text/css" href="' + staticpath +     
    'resources/css/mobile-android.css" /><div class="overlay"></div>
     <div class="new-folder-popup" id="message"><div class="new-folder-popup-bg"><div 
    class="new-folder-header">MEGA for Android</div><div class="new-folder-main-bg">
    <div class="new-folder-descr">Do you want to install the latest<br/> version of the MEGA app for Android?</div><a class="new-folder-input left-b/>');

HTML tags are generated through vanilla JavaScript without using any library. Is this code generated or written by a programmer? And what kind of methods use this style of generating HTML?

I also don't know if determining these is possible by the way.

Some sites use the following JavaScript line to build the site:

document.write('<link rel="stylesheet" type="text/css" href="' + staticpath +     
    'resources/css/mobile-android.css" /><div class="overlay"></div>
     <div class="new-folder-popup" id="message"><div class="new-folder-popup-bg"><div 
    class="new-folder-header">MEGA for Android</div><div class="new-folder-main-bg">
    <div class="new-folder-descr">Do you want to install the latest<br/> version of the MEGA app for Android?</div><a class="new-folder-input left-b/>');

HTML tags are generated through vanilla JavaScript without using any library. Is this code generated or written by a programmer? And what kind of methods use this style of generating HTML?

I also don't know if determining these is possible by the way.

Share Improve this question edited Jan 21, 2015 at 1:43 istos 2,6721 gold badge19 silver badges19 bronze badges asked Jan 16, 2015 at 21:34 cuneyttylercuneyttyler 1,3652 gold badges17 silver badges35 bronze badges 4
  • 9 I doubt many people write code like that professionally. document.write is bad practice, and so is HTML strings like that in your code. Look into the DOM. – elclanrs Commented Jan 16, 2015 at 21:36
  • Unfortunately it's impossible to tell. Some scripts generate this type of code, but there's nothing stopping a developer from doing it by hand too. Best practice would be to use the DOM methods like createElement – Joseph Marikle Commented Jan 16, 2015 at 21:44
  • Thanks for the answers. I'm developing web applications using angularjs and just asked if it was generated or not. – cuneyttyler Commented Mar 27, 2015 at 15:15
  • You can use JS Template Literals: developer.mozilla/de/docs/Web/JavaScript/Reference/… – guettli Commented Mar 16, 2021 at 19:58
Add a ment  | 

2 Answers 2

Reset to default 8

You should not use document.write. You'll find a ton of articles online remending against it and why. Here I'll show you 3 methods to generate HTML via JavaScript, and personally I use all three of them.

Method 1:

This method is simple and works well but it can be error prone when having to type the HTML inside the JS code. Also it mixes HTML and JS together, which isn't really a good practice. Nevertheless, it works and I use this method for simple projects.

Note the ${some_var} syntax. I just came up with that and it isn't specific to JavaScript. We will replace these placeholders with actual values using JavaScript's replace() method and a simple Regular Expression.

// A function that returns an HTML string - a.k.a. a Template
function getHtml() {
  var html = '<div class="entry">';

  html += '<h3 class="title">${title}</h3>';

  html += '<time>';
  html += '<span class="month">${month}</span> ';
  html += '<span class="day">${day}</span>, ';
  html += '<span class="year">${year}</span>';
  html += '</time></div>';

  return html;
}


// Helper function that takes an HTML string & an object to use for
// "binding" its properties to the HTML template above.
function parseTemplate(str, data) {
   return str.replace(/\$\{(\w+)\}/gi, function(match, parensMatch) {
     if (data[parensMatch] !== undefined) {
       return data[parensMatch];
     }

     return match;
   });
 }


 // Now parse the template
 parseTemplate(getHtml(), {
   title: 'Lorem Ipsum',
   month: 'January',
   day: '16',
   year: '2015'
 });

Output:

"<div class="something"><h3 class="title">Lorem Ipsum</h3><time><span class="month">January</span> <span class="day">16</span>, <span class="year">2015</span></time></div>"


Method 2:

This method involves using various DOM methods such as document.createElement() and also works well. The downside is that it can be repetitive, but you can always create your own API out of them like we're doing with the tag() function below.

// Helper function to create an element with attributes
function tag(name, attrs) {
  var el = document.createElement(name.toString());

  !!attrs && Object.keys(attrs).forEach(function(key) {
    el.setAttribute(key, attrs[key]);
  });

  return el;
}


// Now create some DOM nodes
var li = tag('li', {'id': 'unique123', 'data-id': 123, 'class': 'item active'});
var p = tag('p');

// Add text to the paragraph and append it to the list item
p.textContent = 'Lorem ipsum dolor'; // Not cross-browser; more here: https://developer.mozilla/en-US/docs/Web/API/Node.textContent
li.appendChild(p);

// Append the list item to the body
document.body.appendChild(li);

// Or append it somewhere else
document.getElementById('output-div').appendChild(li);
document.querySelector('.content').appendChild(li);

// Other DOM methods/props you can use include:
li.innerHTML = 'some html string';
var txt = document.createTextNode('hello');
// and more...


Method 3:

With this method we use a Template system such as Handlebars (http://handlebarsjs./). It works well when you anticipate to have a lot of templates in a project. Instead of script tags like below, these templates can actually be pre-piled into JavaScript functions too, which is highly remended.

<!-- An HTML template made out of script tags inside your page. -->
<script id="entry-template" type="text/x-handlebars-template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">
      {{body}}
    </div>
  </div>
</script>

Now pile the template:

// Get the HTML source
var source = document.getElementById('entry-template').innerHTML;

// Compile it - `template` here is a function similar to `getHtml()` from the first example
var template = Handlebars.pile(source);

// Provide some data to the template.
var html = template({title: "My New Post", body: "This is my first post!"});

The html variable now contains the following and you can insert it into your page using something like innerHTML:

<div class="entry">
  <h1>My New Post</h1>
  <div class="body">
    This is my first post!
  </div>
</div>

In regards to working with HTML in JS

var div = document.createElement('div');
    div.setAttribute('id', 'mydiv');

document.body.appendChild(div);

This will create a div, give it an ID and append it to the body. This is a much more solid way to work with html in JS. You could also load (or preload) and image like:

var img = new Image();
    img.src = "path to my file";

document.body.appendChild(img);

Hope this helps, feel free to ask me any questions you have.

发布评论

评论列表(0)

  1. 暂无评论