简体   繁体   中英

Convert htmlString to Dom object in Javascript

I made a http request and received a htmlString, now I want to convert it to Dom object to query its elements. Thanks for you help

You can create a container object (I've used a div here) and then assign your html string to .innerHTML and then you can query the child objects that are created.

var container = document.createElement("div");
container.innerHTML = htmlString;

The child nodes of the container object are what is created from your HTML.

using jQuery you could do something like this:

  var yourStringFromServer = '<div><div id="helloWrap"></div></div>';
  var a = $(yourStringFromServer); // create new jQuery instance with string
  a.find('#helloWrap').html('hello'); // find  the helloWrap node and set html
  a.appendTo('body'); // append html to body

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