Reputation: 447
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?
Upvotes: 0
Views: 2274
Reputation: 8297
As was mentioned in the comments, there is no string (prototype) function getElementByID. You are likely thinking of document.getElementById(). To use that, you would have to create an element with document.createElement(), set the innerHTML to the html string, add the element to the DOM (perhaps hidden so it isn't visible) with document.body.appendChild(), then use document.getElementById() (note that the D is lowercase). But that would be creating a temporary container.
jQuery does simplify this a bit. It still requires creating a container but it doesn't have to be appended to the DOM. After creating an element with jQuery() and setting the html with .html(), use jQuery.find() to find the element with the id selector. Then use .html() to get the html contents of the first element found.
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';
var testDiv1 = $('<div>').html(HTMLtext).find('#test-div-1');
console.log(testDiv1.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 21
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';
var tempDom = $('<output>').append($.parseHTML(HTMLtext));
$("#test-div-1",tempDom);
Parse the string to create HTML and create a temporary DOM so that jquery can traverse it.
Upvotes: 1
Reputation: 26163
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...
Upvotes: 4