Search code examples
javascriptjqueryhtmlinnerhtmlgetelementbyid

innerHTML from Javascript String


I have a JavaScript string with HTML content inside it.

e.g.

var HTMLtext = 'text <div id="test-div-1">this is <b>just</b> a div</div><div id="test-div-2">this is <b>just</b> another div</div> more filler text';

I am looking to get the innerHTML from the first div element within this string. When I try using:

var testDiv1 = HTMLtext.getElementByID("test-div-1");

I get the error

HTMLtext.getElementByID is not a function at window.onload

Are there any workarounds without putting HTMLtext in a temporary container?

JSFiddle


Solution

  • Since you have jQuery in the question tags this is very simple...

    var testDiv1 = $("<div/>", { html: HTMLtext }).find("#test-div-1").html();
    

    That creates a non-DOM element, sets the html value and then parses and gets the inner html of the div you want.

    Here's an updated version of your jsfiddle...