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.

3 Answers3

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;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 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. – Brad Christie May 29 '13 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: http://eloquentjavascript.net/chapter3.html. – Felix Kling May 29 '13 at 14:37
  • Then simply stick this in the body of a function called "some_function" and call that. – mgw854 May 29 '13 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 '13 at 14:38
  • @pure_code.com Then wrap it in a function ... – svidgen May 29 '13 at 14:38
  • could this cause a memory leak because firstchild is still referenced by d? like say you were doing something like otherElement.appendChild(d.firstchild); – user210757 Jul 13 '17 at 15:52
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.

NiRUS
  • 3,901
  • 2
  • 24
  • 50
4

jQuery.parseHTML()-function might help you.

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

DonnyDee
  • 386
  • 2
  • 7
  • [`jQuery.parseHTML`](https://github.com/jquery/jquery/blob/master/src/core.js#L455-L480) is just a more elaborate version of [Kolink's answer](http://stackoverflow.com/a/16816777/298053). – Brad Christie May 29 '13 at 14:38
  • Hope this answer helps you: http://stackoverflow.com/a/3104237/2335272 – DonnyDee May 29 '13 at 14:40
  • @DonnyDee that answer will only work for HTML which is XML-valid (i.e. not all HTML). – Paul S. May 29 '13 at 14:44