Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting HTMLElement.classList property

Tags:

javascript

Is it possible to override the HTMLElement.classList property in WebKit (Chrome) ?

I am trying with the following code:

    Object.defineProperty(window.HTMLElement.prototype, "classList", {
        get : function() { 
            console.log("test");
            return 1; 
        },  
        set : function(newValue){  },  
        enumerable : true,  
        configurable : true}
    );  

However, calling classList of a DIV would still return the DOMTokenList.

like image 543
Erik Avatar asked Nov 21 '11 18:11

Erik


2 Answers

Your div is not getting the classList from the prototype. It is a direct property of the div. The prototype chain is never searched:

myDiv.hasOwnProperty("classList"); // returns true
like image 87
gilly3 Avatar answered Oct 14 '22 01:10

gilly3


I guess you should do what you've done with HTMLDivElement, not HTMLElement. However, I did that and still no result.

But if you want to do your job for the moment, you can apply your code directly on the div instance itself:

<div id='target' class='first second third'>
</div>

and:

var div = document.getElementById('target');
Object.defineProperty(div, 'classList', {
    get: function(){
        return 'overridden';
    }
});
alert(div.classList);

See this fiddle.

like image 34
Saeed Neamati Avatar answered Oct 14 '22 02:10

Saeed Neamati