How can I extend a javascript object so that in browsers that initially do not have outerHTML, I can define it?

I found this function (although, I forgot where):

function outerHTML(node){ // if IE, Chrome take the internal method otherwise build one return node.outerHTML || ( function(n){ var div = document.createElement('div'), h; div.appendChild( n.cloneNode(true) ); h = div.innerHTML; div = null; return h; })(node); } 

but this function works by calling outerHTML(my_element) , not my_element.outerHTML

I want to be able to extend the object of the javascript DOM element so that it has an outerHTML element, but use it if it exists anyway. how to do it?

The main reason I want to do this is because Firefox does not have an outerHTML method, but I still want to use my own implementations if they are available, since they passed the test, and I feel I can trust them.

UPDATE: @Raynos suggested that I do not do the above for outerHTML, and I should do something like the outerHTML specification. I found this: How to make outerHTML in firefox? and it does not .cloneNode, which may cause errors in FireFox 8.0.1.
So my solution is this: @Raynos:

 if (!("outerHTML" in HTMLElement.prototype)) { Object.defineProperty(HTMLElement.prototype, "outerHTML", { get: getOuterHTML }); } function getOuterHTML(){ var parent = this.parentNode; var el = document.createElement(parent.tagName); el.appendChild(this.cloneNode(true)); var shtml = el.innerHTML; return shtml; } 
+4
source share
3 answers

You usually do something like:

 if (!("outerHTML" in document.body)) { Object.defineProperty(Element.prototype, "outerHTML", { get: getOuterHTML, set: setOuterHTML }); } 

Then you read the outerHTML specification and write the getOuterHTML and setOuterHTML functions that implement it.

Note. . I highly recommend opposing the naive implementation of the outerHTML property, which is out of specification. This will cause maintenance problems when your "version" works differently than on the native version. Especially if you add additional extensions or additional "features" to your version

Please note that Object.defineProperty undefined in older browsers. You may need to use the gasket from es5-shim

+8
source

Add it to the HTMLElement prototype

 HTMLElement.prototype.outerHTML = function() { // Your implementation of getting outerHTML } 
+1
source

You might want to extend the base Node object, from which almost all DOM extensions, read here for a description of the element element - MDN or as others answered, try the HTMLElement, read here also from MDN - HTMLElement

 Element.prototype.outerHTML = function(){ console.log('hola'); }; HTMLElement.prototype.outerHTML = function(){ console.log('hola'); }; 

like Raynos, in the comments given here is a Spec article that encourages the use of the Element .

Edit: Node links removed

0
source

Source: https://habr.com/ru/post/1385960/


All Articles