Override elements in inline JavaScript object

I would like to override the default behavior of the offsetParent member of all html elements. I would like to do something like this, if possible:

// For <div id="foo"></div>
var oFooElem = document.getElementById("foo");
oFooElem._offsetParent = oFooElem.offsetParent;
oFooElem.prototype.offsetParent = function() {
    window.status = 'offsetParent called.';
    return this._offsetParent;
};

      

Is it possible? If yes, please post the corrected sample code. Thank!

Update:

@some Thank you for your help. It looks like it's impossible. I touched on the issue that caused this question in a new question , if you're interested.

0


source to share


1 answer


As far as I know, this is not possible. In firefox I get an exception "setting a property that only has a getter", IE gives an error, Chrome gives an error, but in Opera it works (if I assign it on an element, not a prototype)!

But you have another problem. offsetParent is not a function, so it will never be called as a function and your warning will never happen. In opera (the only browser I found where you could replace it) you only return a function.

However, you can add a new feature (will work in Firefox, Chrome and Opera, but not IE since IE has no constructor property):

var e = document.getElementById("mydiv"); //Get a div element
//Adds a _offsetParent function to all DIV elements.
e.constructor.prototype._offsetParent=function(){
  alert("offset parent called"); return this.offsetParent;
};
e._offsetParent();

      



Update After reading your description here I see your error:

  • you get a link to myInnerContent object
  • you are removing that object from the DOM when you replace the content of the outer tag.
  • you are trying to get a parent from an old object that is an orphan and that are no longer in the DOM. IE gives you an error and Firefox gives you null.

You already have a solution in your page: Save the object name. You can update the global variable when content is updated if needed, or update only the innerHTML of the inner div.

+3


source







All Articles