Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-25 of 25 total

javascript - dom method for replacing nodes

In addition to removing nodes, the DOM offers a way to replace one node with another. The replaceChild method accomplishes this. As with removeChild above, replaceChild needs to be called from the element that contains the node you wish to replace.

replaceChild takes two arguments: a reference to the new node, and another to the node being replaced. The following example creates a new SPAN element containing a text node, and uses it to replace an existing SPAN.

<script type="text/javascript">
function replaceSpan(){

    var newSpan = document.createElement("span");
    var newText  
	document.createTextNode("on top of the astounded zebra");
    newSpan.appendChild(newText);

    var para = document.getElementById("example3");
    var spanElm = document.getElementById("ex3Span");
    var replaced = para.replaceChild(newSpan,spanElm);
}
</script>


<p id="example3">The quick brown fox jumps <span id="ex3Span">over the lazy dog</span>.</p>


<button onclick="replaceSpan();">Call replaceSpan()</button>

javascript - dom method for removing nodes

You can remove existing nodes as well as add new ones. The removeChild method allows any node to remove one of its child nodes. Simply pass a reference to the node you wish to remove. Any text or elements within the node being removed will be removed along with it.

<script type="text/javascript">

function removeBElm(){

    var para = document.getElementById("example2");

    var boldElm = document.getElementById("example2B");

    var removed = para.removeChild(boldElm);

}
</script>


<p id="example2"><a href="#" onclick="removeBElm(); return false;">Click this link</a> to see the above script in action.</p>

javascript image swap using DOM

Here is a javascript image swap that uses the DOM methods.
It uses them to support swapping images with different sizes.
Just changing the src property causes the swapped images to be distorted in IE.
This script uses replaceChild instead.

var blnDOMSUPPORT = (document.getElementById) ? true : false;
window.onload = window_load;

function window_load()
   {

   if ( blnDOMSUPPORT )
      {

      document.getElementById('icon1').onclick = swapimage;
      document.getElementById('icon2').onclick = swapimage;
      document.getElementById('icon3').onclick = swapimage;
      
      }
   else
      {

      document.images['icon1'].onclick = swapimage;
      document.images['icon2'].onclick = swapimage;
      document.images['icon3'].onclick = swapimage;

      }

   }

function swapimage()
   {
   
   if ( blnDOMSUPPORT )
      {

      var imgMain = document.getElementById('mainimage');
      var divParent;

      // create new image element
      var imgNew = document.createElement('img');

      // give it an image
      // here I use the src of the icon just for convenience
      // you'd want to somehow determine the src of your desired image
      imgNew.src = this.src;
   
      // give it an id
      imgNew.id = 'mainimage';

      // replace image
      divParent = imgMain.parentNode;
      divParent.replaceChild(imgNew, imgMain);

      }
   else
      {

      // old school image swap
      document.images['mainimage'].src = this.src;

      alert( 'old school' );

      }
   
   }         


It would be used with HTML like this
<div id="main">
<img id="mainimage" src="http://www.w3schools.com/css/smiley.gif">
</div>
<div id="icons">
<img id="icon1" src="http://www.w3schools.com/css/smiley.gif">
<img id="icon2" src="http://www.w3schools.com/images/vxhtml.gif">
<img id="icon3" src="http://www.w3schools.com/images/print.gif">
<input type="button" value="Toggle DOM Support" onclick="window.blnDOMSUPPORT = !window.blnDOMSUPPORT;">
</div> 

split value from units

this is a very basic script for seperating out values and units. this is helpful for changing values such as style.top or border.

if element.style.top => '15px'
splitUnit( element.style.top ) => [15,'px']

function splitUnit(e)
/*
*	takes a string and seperates 'px or 'em' from it
*
*	could be streamlined to simply seperate the last two characters, but that could cause errors if used sloppily
*/
{
	if( e && ( length = e.search( /px/ ) ) ) {var eUnit = 'px'; var eValue = e.substr( 0, length );}
	else if( e && ( length = e.search( /em/ ) ) ) {var eUnit = 'em'; var eValue = e.substr( 0, length );}
	else return false;
	
	return new Array( eValue, eUnit );
}

create pre-styled/populated DOM elements

/*
 * create a new DOM element with (optionally) specified className, CSS and text/html content
 * if text contains any markup, it's used as innerHTML value - else a child text node is attached
 * if there's also a parent node given, the new element will be appended as child node
 */
function createStyledElement(tag, parent, cls, css, txt) {
    var el = document.createElement(tag);
    if(cls) el.className = cls;
    if(css) for(var s in css) el.style[s]=css[s];
    if(txt) {
        if (txt.indexOf('<')!=-1) el.innerHTML=txt;
        else el.appendChild(document.createTextNode(txt));
    }
    if(parent) parent.appendChild(el);
    return el;
}

// usage example...
// 1st define some style params
var style1={
    background: '#def',
    color: '#f00',
    padding: '0.5em',
    border: '1px black dotted'
};

createStyledElement(
  'div',
  document.getElementsByTagName('body').item(0),
  null,
  style1,
  'hello <em>world</em>!'
);
« Newer Snippets
Older Snippets »
Showing 21-25 of 25 total