What is the best method to change this object
{
src: \'img.jpg\',
title: \'foo\'
}
into a valid HTML tag string like t
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.
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.
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.
<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>
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']
});
<h1>Awesome People</h1>
<ul>
<li class="first">Paul</li>
<li>Jim</li>
<li>Jane</li>
</ul>
Perhaps slightly more concise than PSL's?
$('<img />',object)[0].outerHTML;
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/
Simple with jquery
$("<div>").append($('<img />',object)).html();