16

Say one 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>';

is it possible to do

var some_element = `some_function`(some_html);

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

2
  • var d = document.createElement('div'); d.innerHTML = some_html; ? May 29, 2013 at 14:33
  • 1
    Try this info https://developer.mozilla.org/en-US/docs/Code_snippets/HTML_to_DOM
    – Eldar
    May 29, 2013 at 14:35

3 Answers 3

48

Create a temporary container for your HTML, then gets its content. Something like:

var d = document.createElement('div');
d.innerHTML = some_html;
return d.firstChild;
6
  • 1
    @pure_code.com: fewer lines of code is not always the best method. Just because there may be a one-liner solution, doesn't mean it's the best implementation. May 29, 2013 at 14:37
  • @pure_code.com: But there isn't. You can put those three lines into a function if you want to (edit: You actually have to since the last line is a return statement). If you don't know how to define functions: eloquentjavascript.net/chapter3.html. May 29, 2013 at 14:37
  • Then simply stick this in the body of a function called "some_function" and call that.
    – mgw854
    May 29, 2013 at 14:37
  • 4
    @pure_code.com Here's a one-liner: var d = document.createElement('div'); d.innerHTML = some_html; return d.firstChild;
    – h2ooooooo
    May 29, 2013 at 14:38
  • @pure_code.com Then wrap it in a function ...
    – svidgen
    May 29, 2013 at 14:38
5

Try the below code

    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 am building a string and appending it to an html element using html() rather than text() function . This will be treated as a HTML tag by browser and diplay the changes in the UI as seen in the fiddle.

2
  • Don't forget to add an explanation to your code for those who might not be familiar with jQuery or JavaScript.
    – Jeff Noel
    Jun 18, 2013 at 18:28
  • That JQUERY code is perfect. Thank you!
    – BossWalrus
    Mar 28, 2015 at 22:18
4

jQuery.parseHTML()-function might help you.

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

3