' + '

Convert HTML string to DOM element?

Say he has

var some_html = '<div class = "am_hold">' + '<img name="bo_im" id="' + val.id + '" class="bookmark_image" src="' + val.favicon + '">' + '<a target="_blank" name="bookmark_link" class="bookmark_link" href = "' + val.url + '" id="' + val.id + '">' + val.title + '</a>' + '<div><div class = "bookmark_menu"></div></div>' + '</div>'; 

can do

 var some_element = `some_function`(some_html); 

Is there an implementation for some_function (1) without using a library and (2) using a library.

+8
javascript html
source share
3 answers

Create a temporary container for your HTML, then get its contents. Something like:

 var d = document.createElement('div'); d.innerHTML = some_html; return d.firstChild; 
+34
source share

Try the code below

  var myname = 'John Doe'; //This is using Jquery var htmltext = '<p style="color:red">'+myname+'This is a test</p>' $('#one').html(htmltext); //This is pure javascript document.getElementById('two').innerHTML='<p style="color:red">'+myname+'This is a test</p>'; 

JSfiddle link

I create a string and add it to the html element using the html () function, not the text () function. This will be considered as an HTML tag by the browser and change the changes in the user interface, as shown in the fiddle.

+5
source share

JQuery.parseHTML () function can help you.

http://api.jquery.com/jQuery.parseHTML/

+4
source share

All Articles