There is no doubt that as can be seen from the above code, when you click on the A tag, "Hello" will pop up. tagA is a DOM element, except for onclick In addition to events, there are onmouseover, onmouseout, onmousemove, etc., and these events are all inherent in the DOM element itself; but now we want to extend it, for example, to make it support tagA.bind, I can use tagA.bind( "click",function(){}), instead of tagA.onclick=function(){}. OK, the purpose is very clear now. Let’s look at the following code first:
Copy the code The code is as follows:




DOM function extension

Hello




The above This piece of code is the final result after the function is expanded. It has the same function as the previous piece of code, but it cannot be executed now. It needs to be extended. Before that, let’s take a look at some basic knowledge. This is very important. Because we will use it later:
1. HTMLElement. In the DOM standard, each element inherits from HTMLElement, and HTMLElement inherits from Element, and Element inherits from Node; so we can use the prototype of HTMLElement to extend HTML. How to implement the methods and attributes of elements? Let’s look at a piece of code:
Copy code The code is as follows:




DOM function extension


                                                                !--
HTMLElement.prototype.Alert=function(){
alert("This is an extension method");
}
var tagA=document.getElementById("tagA");
tagA.Alert();
//-->





The above code will pop up "This is an extension method" when the page is loaded. However, I believe you have noticed that it will error in IE6, 7, and 8, but it will not work in IE9 or above or in browsers such as Chrome, Firefox, and Opera. Everything runs normally inside. This is a compatibility issue. Don't worry, it will be solved later.
The above code is not flexible enough. Let’s optimize it to make it more flexible:
Copy the code The code is as follows:




DOM function extension


Hello
Hello
< ;script type="text/javascript">