Create a DOM document from string, without JQuery

后端 未结 9 473
梦如初夏
梦如初夏 2020-12-05 14:12

We\'re looking for ways to create a DOM document in javascript from a string, but without using Jquery. Is there a way to do so? [I would assume so, since J

9条回答
  •  遥遥无期
    2020-12-05 14:20

    In case you're still looking for an anwer, and for anyone else coming accross it, I just have been trying to do the same thing myself. It seems you want to be looking at javascript's DOMImplementation:

    http://reference.sitepoint.com/javascript/DOMImplementation

    There are few references to compatibility as well here, but it's fairly well supported.

    In essence, to create a new document to manipulate, you want to create a new Doctype object (if you're going to output some standards based stuff) and then create the new Document using the newly created Doctype variable.

    There are multiple options to be put into both the doctype and the document, but if you're creating an HTML5 document, it seems you want to leave most of them as blank strings.

    Example (New HTML5 DOM Document):

    var doctype = document.implementation.createDocumentType( 'html', '', '');
    
    var dom = document.implementation.createDocument('', 'html', doctype);
    

    The new Document now looks like this:

    
    
    
    

    Example (New XHTML DOM Document):

    var doctype = document.implementation.createDocumentType(
        'html',
        '-//W3C//DTD XHTML 1.0 Strict//EN',
        'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
    );
    
    var dom = document.implementation.createDocument(
        'http://www.w3.org/1999/xhtml',
        'html',
        doctype
    );
    

    So it's up to you to populate the rest of it. You could do this as simply as changing

    dom.documentElement.innerHTML = '';
    

    Or go with the more rigorous:

    var head = dom.createElement( 'head' );
    var body = dom.createElement( 'body' );
    dom.documentElement.appendChild(head);
    dom.documentElement.appendChild(body);
    

    All yours.

提交回复
热议问题