Create HTML tag from Javascript object

前端 未结 6 2073
清歌不尽
清歌不尽 2021-02-19 06:21

What is the best method to change this object

{
    src: \'img.jpg\',
    title: \'foo\'
}

into a valid HTML tag string like t

相关标签:
6条回答
  • 2021-02-19 06:32

    Making html elements based out of objects containing attribute-attribute values such as

    {
        src: 'img.jpg',
        title: 'foo'
    }
    

    almost completely falls into the paradigm of cook.js.
    The command which you would issue with cook would be:

    img ({
        src: 'img.jpg',
        title: 'foo'
    })
    

    If the attribute details are stored as given in your example,
    in a variable obj then:

    img(obj)
    

    For more details check it out at cook.relfor.co.

    0 讨论(0)
  • 2021-02-19 06:39

    Why not:

    $('<img/>', obj).get(0).outerHTML;
    

    Fiddle

    You do not need to wrap it in a div using multiple functions and get the html, just use get(0) to get the DOM element and outerHTML to get the element's html representation.

    Unless you are using browsers really old you can rely on outerHTML

    Here is a JSPerf to compare the performance diff between the approaches.

    0 讨论(0)
  • 2021-02-19 06:41

    If you are only doing one element, then this solution is overkill, but I thought I would post it anyway as I don't know what your project is.

    Have you considered a JavaScript template engine? I've been playing around with Swig lately, as it is quite lightweight, but there are many options. Basically, you create a template, pass a JavaScript object, and the compiled template is executed, returning a string of HTML.

    Example from Swig Documentation

    Template

    <h1>{{ pagename|title }}</h1>
    <ul>
    {% for author in authors %}
      <li{% if loop.first%} class="first"{% endif %}>
        {{ author }}
      </li>
    {% else %}
      <li>There are no authors.</li>
    {% endfor %}
    </ul>
    

    JavaScript to Render Template

    var template  = require('swig');
    var tmpl = template.compileFile('/path/to/template.html');
    tmpl.render({ // The return value of this function is your output HTML
        pagename: 'awesome people',
        authors: ['Paul', 'Jim', 'Jane']
    });
    

    Output

    <h1>Awesome People</h1>
    <ul>
      <li class="first">Paul</li>
      <li>Jim</li>
      <li>Jane</li>
    </ul>
    
    0 讨论(0)
  • 2021-02-19 06:43

    Perhaps slightly more concise than PSL's?

    $('<img />',object)[0].outerHTML;
    
    0 讨论(0)
  • 2021-02-19 06:44

    Here's how you make it as a string:

    var img = '<img ',
        obj = { src : 'img.jpg', title: 'foo' };
    
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        img += prop + '=' + '"' + obj[prop] + '" ';
      }
    }
    
    img += '/>';
    

    http://jsfiddle.net/5dx6e/

    EDIT: Note that the code answers the precise question. Of course it's unsafe to create HTML this way. But that's not what the question asked. If security was OP's concern, obviously he/she would use document.createElement('img') instead of a string.

    EDIT 2: For the sake of completeness, here is a much safer way of creating HTML from the object:

    var img = document.createElement('img'),
        obj = { src : 'img.jpg', title: 'foo' };
    
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        img.setAttribute(prop, obj[prop]);
      }
    }
    

    http://jsfiddle.net/8yn6Y/

    0 讨论(0)
  • 2021-02-19 06:48

    Simple with jquery

    $("<div>").append($('<img />',object)).html();
    
    0 讨论(0)
提交回复
热议问题