Converting HTML string into DOM elements?

This question already has an answer here:

  • Creating a new DOM element from an HTML string using built-in DOM methods or Prototype 19 answers

  • 您可以使用DOMParser ,如下所示:

    var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>"
      , parser = new DOMParser()
      , doc = parser.parseFromString(xmlString, "text/xml");
    doc.firstChild // => <div id="foo">...
    doc.firstChild.firstChild // => <a href="#">...
    

    You typically create a temporary parent element to which you can write the innerHTML , then extract the contents:

    var wrapper= document.createElement('div');
    wrapper.innerHTML= '<div><a href="#"></a><span></span></div>';
    var div= wrapper.firstChild;
    

    If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li> , you'd have to have the parent wrapper be a <ul> .

    But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr> ... </tr></tbody></table> , write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.


    Why not use insertAdjacentHTML

    for example:

    // <div id="one">one</div> 
    var d1 = document.getElementById('one'); 
    d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
    
    // At this point, the new structure is:
    // <div id="one">one</div><div id="two">two</div>here
    
    链接地址: http://www.djcxy.com/p/83328.html

    上一篇: 如何判断元素的哪一部分在视口内?

    下一篇: 将HTML字符串转换为DOM元素?