I. clearAttributes ()
This method is used to clear all user-defined attributes. As follows:
Copy codeThe Code is as follows:
<Div style = "color: red;" onclick = "alert (1)" data-a = "a" data-B = "B"> Division </div>
<Script>
Var div = document. getElementsByTagName ('div ') [0];
Alert (div. outerHTML );
Div. clearAttributes ();
Alert (div. outerHTML );
</Script>
The following pop-up is displayed after running:
We can see that the outerHTML output by alert for the second time has no "data-a", "data-B", and "onclick = alert (1)" attributes. The first two attributes are user-defined, and The onclick attribute is user-defined but also cleared.
Although outerHTML is cleared, the event is not actually cleared. Click div and 1 is displayed. (Note: For Element Free attributes such as id, name, and style, they will not be cleared)
The preceding figure shows that although the onclick attribute is deleted in outerHTML, the event handler is not deleted, and the click can still be triggered. Can events added through attachEvent be cleared? Try it
Copy codeThe Code is as follows:
<Div> division </div>
<Script>
Var div = document. getElementsByTagName ('div ') [0];
Div. attachEvent ('onclick', function () {alert (1 )});
Div. clearAttributes ();
</Script>
Test results show that clicking this div in IE6/7/8 does not bring up 1, but IE9 still pops up. That is, the event handler added by attachEvent cannot be cleared by clearAttributes in IE9.
Ii.. mergeAttributes ()
This method is used to copy all of the specified elements to itself, including attributes, events, and styles. As follows:
Copy codeThe Code is as follows:
<Div id = "head" style = "color: red;" onclick = "alert (1)" data-a = "a"> Division </div>
<P> paragraph </p>
<Script>
Var div = document. getElementsByTagName ('div ') [0];
Var p = document. getElementsByTagName ('P') [0];
Alert (p. outerHTML );
P. mergeAttributes (div );
Alert (p. outerHTML );
</Script>
Copy the previous p's outerHTML
Copy p's outerHTML
After comparison, we can see that div's style (styles), onclick (events), and data-a (user-defined attributes) are all copied to p. Now, you can click "p" to generate 1 for alert.
Careful colleagues found that the div id was not copied. Indeed, before IE5, attributes was read-only and id/name was not merged. After IE5.5, you can specify the second parameter value to determine whether to copy the id/name attribute.
You only need to specify the second parameter of mergeAttributes as false to copy the id/name. For example
P. mergeAttributes (div, false );
Effect
Related:
Http://msdn.microsoft.com/en-us/library/ie/ms536350%28v=vs.85%29.aspx
Http://msdn.microsoft.com/en-us/library/ie/ms536614%28v=vs.85%29.aspx