简体   繁体   中英

How do you check if a JavaScript Object is a new DOM Element?

I have a function

mutationToDom: function() {
    var container = document.createElement( 'mutation' );

    container.setAttribute( 'string', 'test' );

    return container;
}

The container is <mutation string="test"></mutation>

How can I check it after I call this function in my Unit test?

QUnit.test( 'check function mutationToDom', function( assert ) {
    var container = testBlock.mutationToDom();
    assert.ok( container === ???, 'mutation is created with correct value' );
});

Try #1

I tried with XMLSerializer() to convert the XML to string

var containerString = new XMLSerializer().serializeToString(container);

but, the containerString is

"<mutation xmlns="http://www.w3.org/1999/xhtml" string="test"></mutation>"

instead of "<mutation string="test"></mutation>"

How about checking for the outerHTML ?

 var testBlock = { mutationToDom: function() { var container = document.createElement('mutation'); container.setAttribute('string', 'test'); return container; } }; QUnit.test( 'check function mutationToDom', function( assert ) { var container = testBlock.mutationToDom(); assert.ok( container.outerHTML === '<mutation string="test"></mutation>', 'mutation is created with correct value' ); }); 
 <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.6.0.css"> <div id="qunit"></div> <div id="qunit-fixture"></div> <script src="https://code.jquery.com/qunit/qunit-2.6.0.js"></script> 

To answer the specific question in the title, try testObject instanceof Element or ...HTMLElement ? This might be a precondition of checking the .outerHTML , as suggested by 31piy.

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