May 19, 2000 - Merging Objects | WebReference

May 19, 2000 - Merging Objects

Yehuda Shiran May 19, 2000
Merging Objects
Tips: May 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The mergeAttributes() method copies all read/write attributes to the specified element. The syntax is as follows:

<targetObject>.mergeAttributes(sourceObject [, preserveFlag]);
The first parameter, sourceObject, is the object from which we copy the attributes to the object that invokes mergeAttributes(), <targetObject>, and is required. The second parameter, preserveFlag, specifies whether to overwrite targetObject's attributes having the same name as the sourceObject's attributes (true for preserving and false for overwriting). This parameter is optional and has introduced only in IE 5.5. In Internet Explorer 5.0 and earlier, attributes that are read only, such as ID, are not merged. As of IE 5.5, you can choose not to preserve the identity of the targetObject and merge all attributes of an object, including ID and NAME. The mergeAttribute() method copies attributes, events, and styles.

The following example shows the usage of the mergeAttributes() with and without the optional preserveFlag flag. Move your mouse over the next two DIV elements. Notice the color change when you go over the top element. The top one supports the onmouseover, onmouseout, and onclick event handlers, while the bottom one does not. Now, click the "Merge Attributes" button below, and check again the two DIV elements above. Notice that the bottom DIV now has all the event handlers and attributes that the top one has. As a further proof, you also get an alert box with the HTML description of the bottom element. Again, you can notice all the elements and handlers that the top one has.

Currently, the two buttons yields the same results. The attribute ATTRIBUTE1 of the top element always overwrites the corresponding attribute of the bottom one.

This is a sample DIV element.
This is another sample DIV element.

This is a sample DIV element.
This is another sample DIV element.

Here is the code for the first section above:

function mergeObjectsTrue() {
  two.children[1].mergeAttributes(two.children[0], true);
// -->
<SPAN ID="two">
  <DIV  ATTRIBUTE1="true" ATTRIBUTE2="true"
    onclick="alert('click');" onmouseover="'#0000FF';"
    This is a sample <b>DIV</b> element.
  <DIV  ATTRIBUTE1="false">
    This is another sample <b>DIV</b> element.
  <INPUT TYPE="button" VALUE="Merge Attributes -- Preserve"     onclick="mergeObjectsTrue()"><BR>