What is the best method to change this object
{
src: 'img.jpg',
title: 'foo'
}
into a valid HTML tag string like this
<img src="img.jpg" title="foo" />
Solution 1
With jQuery this is easy; but complicated:
$('<img/>').attr(obj).wrap('<div/>').parent().html();
Any better ideas?
Inside the function, we first get the reference of the <div> and <p> element of HTML. Then we create an <h2> element using createElement() method. To insert it before the <p> element we use the insertBefore() method where we pass the newly created <h2> tag and the <p> tag reference as parameters.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With