📜 ⬆️ ⬇️

We learn InternetExplorer to good: we expand prototypes of DOM elements.

I had a problem expanding standard HTMLElement objects, but not in Firefox, but in IE. You can use the library Prototype or JSX. But I did not like this decision due to the fact that the add-in is used, and not the eye-catching mechanism for accessing elements through the DOM. For example, I want a new method to appear in IE
  someDOMElement.getLastChild () 


In Firefox, I would write:
 HTMLElement.prototype.getLastChild = function ()
 {
	 var childndex = null;
	 for (i = this.childNodes.length; i> 0; i--)
	 {
		 if (this.childNodes [i-1] .nodeType! = 1)
			 continue;
		 childIndex = i-1;
		 break;
	 }
	 return this.childNodes [childIndex];
 }


In IE, this chip does not work, due to the clumsy support in it of the objectiveness of the elements. Although, all the objects in it are of class Object or its derived Element, but they cannot be extended. You can only each specific instance (run through all the DOM elements of the document). The solution was found in the HTC technology (HTML Components), which is supported since IE5.5

I will not go into details, but I will immediately move on to how this is done (often this is enough to understand the details):
 <PUBLIC: COMPONENT lightWeight = "true" literalContent = "true">
	 <PUBLIC: METHOD NAME = "getLastChild" />
	 <SCRIPT LANGUAGE = "javascript1.3" type = "text / javascript">
	 function getLastChild ()
	 {
		 var childndex = null;
		 for (i = childNodes.length; i> 0; i--)
		 {
			 if (childNodes [i-1] .nodeType! = 1)
				 continue;
			 childIndex = i-1;
			 break;
		 }
		 return childNodes [childIndex];
	 }
	 </ SCRIPT>
 </ PUBLIC: COMPONENT>

')
<PUBLIC: COMPONENT lightWeight = "true" literalContent = "true">
means the beginning of a component definition. lightWeight means, briefly, that there is nothing other than a description. literalContent means that the code will not be parsed by the XHTML parser, but transferred immediately to the Javascript parser.

The code above should be placed in a separate file with the extension ".htc". Connect to the page better in the conditional comments:
 <! - [if IE]>
 <style>
 * {
 behavior: URL ('/ uri / to / file.htc');
 }
 </ style>
 <[endif] ->


now the code is:
 var el = document.getElementsByTagName ("body") [0] .getLastChild ();

will work in both FF and IE.

To work in Opere and other browsers such code will not, unfortunately. But, I think, I will find (or someone will tell) how to implement it in other browsers.

Naturally, HTC technology is not limited to this and allows you to add new events, properties, default values, as well as create your own tags.

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


All Articles