Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML tag from Javascript object

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?

like image 352
Marc Avatar asked Jun 27 '13 03:06

Marc


People also ask

How do you create a new h2 element using JavaScript?

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.


1 Answers

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.

like image 111
PSL Avatar answered Sep 28 '22 13:09

PSL