简体   繁体   中英

innerHTML from Javascript String

I have a JavaScript string with HTML content inside it.

eg

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

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...

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM