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 1-10 of 26 total  RSS 

Fire Javascript DOM events

Fire Javascript DOM events

   1  function fireEvent(obj, evt) {
   2    var fireOnThis = obj;
   3    if (document.createEvent) {
   4      var evObj = document.createEvent("MouseEvents");
   5      evObj.initEvent(evt, true, false);
   6      fireOnThis.dispatchEvent(evObj);
   7    else if (document.createEventObject) {
   8      fireOnThis.fireEvent("on" + evt);
   9    }
  10  }


Usage: clicking on a link using Javascript

HTML
   1  <a href="foo.html" id="fooanchor" style="display: none>Nothing to see here</a>

Javascript
   1  fireEvent(document.getElementById('fooanchor'), "click")

Firefox 3 and input file

The nsIDOMFile interface retrieves data from a file submitted to a form using the input type "file". This allows the file reference to be saved when the form is submitted while the user is using a web application offline, so that the data can be retrieved and uploaded once the Internet connection is restored.

   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3  	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  
   5  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   6  <head>
   7  	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   8  	<title>input type=file & Firefox 3</title>
   9  </head>
  10  
  11  <body>
  12  	
  13  <h1>input type=file & Firefox 3</h1>
  14  	
  15  <script type="text/javascript">
  16  // <![CDATA[
  17  
  18  function inputFileOnChange() {
  19  	var v_console = '';
  20  	v_console += 'value: ' + document.getElementById('my-file').value;
  21  	v_console += '<br \/>';
  22  	
  23  	if(document.getElementById('my-file').files) {
  24  		// Support: nsIDOMFile, nsIDOMFileList
  25  		v_console += 'files.length: ' + document.getElementById('my-file').files.length;
  26  		v_console += '<br \/>';
  27  		
  28  		v_console += 'fileName: ' + document.getElementById('my-file').files.item(0).fileName;
  29  		v_console += '<br \/>';
  30  		
  31  		v_console += 'fileSize: ' + document.getElementById('my-file').files.item(0).fileSize;
  32  		v_console += '<br \/>';
  33  		
  34  		v_console += 'data: ' + document.getElementById('my-file').files.item(0).getAsDataURL();
  35  //		v_console += 'data: ' + document.getElementById('my-file').files.item(0).getAsBinary();
  36  //		v_console += 'data: ' + document.getElementById('my-file').files.item(0).getAsText();
  37  		v_console += '<br \/>';
  38  	};
  39  	
  40  	document.getElementById('console').innerHTML = v_console;
  41  };
  42  
  43  // ]]>
  44  </script>
  45  	
  46  <div>
  47  	<input type="file" name="my-file" id="my-file" onchange="inputFileOnChange();" />
  48  	<br /><br />
  49  	<code id="console">...console...< /code>
  50  </div>
  51  	
  52  </body>
  53  </html>


Source: Firefox 3 and input type=file , upload file

JavaScript Function checks for DOM Element visibility

Determines if a given element is visible, by checking a variety of things. Will work for CSS or inline style declarations of visible:hidden or display: none. Will check if it's inside of an invisible element, as well.

   1  
   2  function isVisible(obj)
   3  {
   4      if (obj == document) return true
   5      
   6      if (!obj) return false
   7      if (!obj.parentNode) return false
   8      if (obj.style) {
   9          if (obj.style.display == 'none') return false
  10          if (obj.style.visibility == 'hidden') return false
  11      }
  12      
  13      //Try the computed style in a standard way
  14      if (window.getComputedStyle) {
  15          var style = window.getComputedStyle(obj, "")
  16          if (style.display == 'none') return false
  17          if (style.visibility == 'hidden') return false
  18      }
  19      
  20      //Or get the computed style using IE's silly proprietary way
  21      var style = obj.currentStyle
  22      if (style) {
  23          if (style['display'] == 'none') return false
  24          if (style['visibility'] == 'hidden') return false
  25      }
  26      
  27      return isVisible(obj.parentNode)
  28  }

Generating Taconite command documents

// description of your code here
Hello,

This is a port of a php class used to generate XML taconite command documents, useful for (very) easy and powerful ajaxy stuff, if you don't know what that is just check it there in french : http://www.desfrenes.com/playground/taconite/ or there in english : http://www.malsup.com/jquery/taconite/.

Basically what it does is generate an XML document that is later processed by a javascript plugin which executes a serie of DOM modifications.

About the code, I'm a Django beginner as well as a Python beginner so kind advices are welcome.

Cheers.
   1  
   2  # usage:
   3  #
   4  # t = Taconite()
   5  #
   6  # t.append("#toto","<label>test</label>")
   7  # t.remove("#tutu")
   8  # t.js('alert("hello world");')
   9  # t.toggleClass('blue','body')
  10  # t.css("body","background-color","white")
  11  # [...]
  12  # print t.toprettyxml()
  13  
  14  import xml.dom.minidom as dom
  15  
  16  class Taconite(dom.Document):
  17      def __init__(self):
  18          dom.Document.__init__(self)
  19          taconite = self.createElement("taconite")
  20          self.appendChild(taconite)
  21  
  22      def __str__(self):
  23          return self.toxml(encoding="utf-8")
  24      
  25      def camelizeCssProperty(self,property):
  26          words = property.split('-')
  27          camelized = words[0].lower()
  28          for word in words[1:] :
  29              camelized = camelized + word[0].upper() + word[1:]
  30          return camelized
  31      
  32      def js(self,script):
  33          command = self.createElement("eval")
  34          js = self.createTextNode(script)
  35          command.appendChild(js)
  36          self.childNodes[0].appendChild(command)
  37      
  38      def changeContentCommand(self,method,selector,content):
  39          html_dom = dom.parseString(content)
  40          command = self.createElement(method)
  41          command.setAttribute("select",selector)
  42          command.appendChild(html_dom.childNodes[0])
  43          self.childNodes[0].appendChild(command)
  44      
  45      def changeStateCommand(self,action,selector):
  46          command = self.createElement(action)
  47          command.setAttribute("select",selector)
  48          self.childNodes[0].appendChild(command)
  49      
  50      def CssCommand(self,action,css_class,selector):
  51          command1 = self.createElement(action)
  52          command1.setAttribute("select",selector)
  53          command1.setAttribute("arg1",css_class)
  54          command2 = self.createElement(action)
  55          command2.setAttribute("select",selector)
  56          command2.setAttribute("value",css_class)
  57          self.childNodes[0].appendChild(command1)
  58          self.childNodes[0].appendChild(command2)
  59      
  60      def addClass(self,css_class,selector):
  61          self.CssCommand("addClass",css_class,selector)
  62  
  63      def removeClass(self,css_class,selector):
  64          self.CssCommand("remove",css_class,selector)
  65  
  66      def toggleClass(self,css_class,selector):
  67          self.CssCommand("toggleClass",css_class,selector)
  68      
  69      def append(self,selector,content):
  70          self.changeContentCommand("append",selector,content)
  71      
  72      def prepend(self,selector,content):
  73          self.changeContentCommand("prepend",selector,content)
  74          
  75      
  76      def before(self,selector,content):
  77          self.changeContentCommand("before",selector,content)
  78          
  79      
  80      def after(self,selector,content):
  81          self.changeContentCommand("after",selector,content)
  82      
  83      def wrap(self,selector,content):
  84          self.changeContentCommand("wrap",selector,content)
  85      
  86      def replace(self,selector,content):
  87          self.changeContentCommand("replace",selector,content)
  88      
  89      def replaceContent(self,selector,content):
  90          self.changeContentCommand("replaceContent",selector,content)
  91      
  92      def remove(self,selector):
  93          self.changeStateCommand("remove",selector)
  94      
  95      def show(self,selector):
  96          self.changeStateCommand("show",selector)
  97      
  98      def hide(self,selector):
  99          self.changeStateCommand("hide",selector)
 100      
 101      def removeContent(self,selector):
 102          self.changeStateCommand("empty",selector)
 103      
 104      def css(self,selector,property,value):
 105          command = self.createElement("css")
 106          command.setAttribute("select",selector)
 107          command.setAttribute("name",self.camelizeCssProperty(property))
 108          command.setAttribute("value",value)
 109          self.childNodes[0].appendChild(command)

Reference of keyCodes

   1  
   2      switch (oEvent.keyCode) {
   3         case 38: //up arrow  
   4         case 40: //down arrow
   5         case 37: //left arrow
   6         case 39: //right arrow
   7         case 33: //page up  
   8         case 34: //page down  
   9         case 36: //home  
  10         case 35: //end                  
  11         case 13: //enter  
  12         case 9: //tab  
  13         case 27: //esc  
  14         case 16: //shift  
  15         case 17: //ctrl  
  16         case 18: //alt  
  17         case 20: //caps lock
  18         case 8: //backspace  
  19         case 46: //delete
  20             return true;
  21             break;
  22  
  23         default: 

Note: When capturing combination keys there is dedicated boolean attributes for each of the special keys (CTRL, SHIFT, ALT).
Reference: Make Life Easy With Autocomplete Textboxes [JavaScript & AJAX Tutorials] [sitepoint.com]

insertAfter() with insertBefore() and node.nextSibling

insertAfter() with insertBefore() and node.nextSibling

   1  
   2  Node.prototype.insertAfter = function(newNode, refNode) {
   3  	if(refNode.nextSibling) {
   4  		return this.insertBefore(newNode, refNode.nextSibling);
   5  	} else {
   6  		return this.appendChild(newNode);
   7  	}
   8  }


Source: Benoit Asselin

Include CSS Stylesheet by DOM

   1  
   2  
   3  function includeCSS(p_file) {
   4  	var v_css  = document.createElement('link');
   5  	v_css.rel = 'stylesheet'
   6  	v_css.type = 'text/css';
   7  	v_css.href = p_file;
   8  	document.getElementsByTagName('head')[0].appendChild(v_css);
   9  }
  10  


Source: Document Object Model (DOM) Level 1 Specification

DOM Mouse-Over Element Selection and Isolation

DOM ISO.v.0.3.0.7.bookmarklet.js
bookmarklet for selecting and isolating an element on a page.

two sections:
section 1: Mouseover DOM, setup and handle mouse events and show information about element in informational div. Click to select, Any key to cancel.
section 2: Element Isolation with help of XPath. prompt user for XPath expression e.g., //DIV[@id='post-body']. then use XPath to select all elements not(ancestor or descendant or self), then delete those elements. also ignore self-or-descendants of head and title.

tools:
Ruderman's javascript development environment: https://www.squarefree.com/bookmarklets/webdevel.html#jsenv
Mielczarek's js to bookmarklet generator: http://ted.mielczarek.org/code/mozilla/bookmarklet.html

   1  
   2  
   3  (function() {
   4  	//GLOBALS
   5  		//globals for classMausWork
   6  		var gSelectedElement;	//currently only one selection
   7  		var gHoverElement;		//whatever element the mouse is over
   8  		var gHovering=false;	//mouse is over something
   9  		var gObjArrMW=[];	//global array of classMausWork objects.  for removing event listeners when done selecting.
  10  		
  11  		//extended	
  12  		var infoDiv;		//currently just container for InfoDivHover, might add more here
  13  		var infoDivHover;	//container for hoverText text node.
  14  		var hoverText;		//show information about current element that the mouse is over
  15  		//const EXPERIMENTAL_NEW_CODE=true;	//debugging. new features.
  16  	
  17  	
  18  	//START
  19  	SetupDOMSelection();	
  20  
  21  
  22  
  23  		
  24  	//(Section 1) Element Selection
  25  	function SetupDOMSelection()
  26  	{
  27  
  28  		{
  29  			//setup event listeners
  30  			//var pathx="//div | //span | //table | //td | //tr | //ul | //ol | //li | //p";
  31  			var pathx="//div | //span | //table | //th | //td | //tr | //ul | //ol | //li | //p | //iframe";
  32  			var selection=$XPathSelect(pathx);
  33  			for(var element, i=0;element=selection(i);i++)
  34  			{			
  35  				if(element.tagName.match(/^(div|span|table|td|tr|ul|ol|li|p)$/i))	//redundant check.
  36  				{
  37  					var m = new classMausWork(element);
  38  					gObjArrMW.push(m);
  39  					attachMouseEventListeners(m);
  40  				}
  41  			}
  42  			document.body.addEventListener('mousedown',MiscEvent,false);
  43  			document.body.addEventListener('mouseover',MiscEvent,false);
  44  			document.body.addEventListener('mouseout',MiscEvent,false);
  45  			document.addEventListener('keypress',MiscEvent,false);
  46  		}
  47  		{
  48  			//setup informational div to show which element the mouse is over.
  49  			infoDiv=document.createElement('div');
  50  			var s=infoDiv.style;
  51  			s.position='fixed';
  52  			s.top='0';
  53  			s.right='0';
  54  			
  55  			s.display='block';
  56  			s.width='auto';
  57  			s.padding='0px';
  58  
  59  			document.body.appendChild(infoDiv);
  60  			infoDivHover=document.createElement('div');
  61  
  62  			s=infoDivHover.style;
  63  			s.fontWeight='bold';			
  64  			s.padding='3px';
  65  			s.Opacity='0.8';
  66  			s.borderWidth='thin';
  67  			s.borderStyle='solid';
  68  			s.borderColor='white';
  69  			s.backgroundColor='black';
  70  			s.color='white';
  71  			
  72  			infoDiv.appendChild(infoDivHover);			
  73  			hoverText=document.createTextNode('selecting');
  74  			infoDivHover.appendChild(hoverText);
  75  		}
  76  	}
  77  	
  78  	function CleanupDOMSelection()
  79  	{
  80  		for(var m; m=gObjArrMW.pop(); )
  81  		{
  82  			detachMouseEventListeners(m);
  83  		}
  84  		ElementRemove(infoDiv);
  85  		document.body.removeEventListener('mousedown',MiscEvent,false);
  86  		document.body.removeEventListener('mouseover',MiscEvent,false);
  87  		document.body.removeEventListener('mouseout',MiscEvent,false);		
  88  		document.removeEventListener('keypress',MiscEvent,false);
  89  	}	
  90  
  91  	function attachMouseEventListeners(c)
  92  	{
  93  		//c is object of class classMausWork
  94  		c.element.addEventListener("mouseover",c.mouse_over,false);				
  95  		c.element.addEventListener("mouseout",c.mouse_out,false);	
  96  		c.element.addEventListener("mousedown",c.mouse_click,false);		
  97  	}
  98  
  99  	function detachMouseEventListeners(c)
 100  	{
 101  		//c is object of class classMausWork
 102  		c.resetElementStyle();
 103  		c.element.removeEventListener("mouseover",c.mouse_over,false);				
 104  		c.element.removeEventListener("mouseout",c.mouse_out,false);	
 105  		c.element.removeEventListener("mousedown",c.mouse_click,false);		
 106  	}
 107  
 108  	//mouse event  handling class for element, el.
 109  	function classMausWork(element)
 110  	{	
 111  		//store information about the element this object is assigned to handle. element,  original style, etc.	
 112  		this.element=element;
 113  		
 114  		var elementStyle=element.getAttribute('style');
 115  		var target;
 116  		
 117  		this.mouse_over=function(ev)
 118  		{	
 119  			if(gHovering)return;
 120  			var e=element;			
 121  			var s=e.style;
 122  			s.backgroundColor='yellow';
 123  			s.borderWidth='thin';
 124  			s.borderColor='lime';
 125  			s.borderStyle='solid';					
 126  			InfoMSG(ElementInfo(e),'yellow','blue','yellow');
 127  			gHoverElement=e;
 128  			gHovering=true;
 129  			target=ev.target;
 130  			ev.stopPropagation();		
 131  		};
 132  		
 133  		this.mouse_out=function(ev)
 134  		{
 135  			if(!gHovering)return;
 136  			if(gHoverElement!=element ||ev.target!=target)return;
 137  			var e=element;
 138  			e.setAttribute('style',elementStyle);
 139  			InfoMSG('-','white','black','white');	
 140  			gHoverElement=null;
 141  			gHovering=false;
 142  			target=null;
 143  			//ev.stopPropagation();
 144  		};
 145  		
 146  		this.mouse_click=function(ev)
 147  		{
 148  			if(!gHovering)return;
 149  			if(gHoverElement!=element ||ev.target!=target)return;
 150  			var e=element;
 151  			e.setAttribute('style',elementStyle);
 152  			ev.stopPropagation();			
 153  			CleanupDOMSelection();			
 154  			gHoverElement=null;
 155  			gHovering=false;
 156  			target=null;
 157  			
 158  			if(ev.button==0)
 159  			{
 160  				gSelectedElement=e;
 161  				ElementSelected(e);	//finished selecting, cleanup then move to next part (section 2), element isolation.
 162  			}
 163  		};
 164  		
 165  		this.resetElementStyle=function()
 166  		{
 167  			element.setAttribute('style',elementStyle);
 168  		};		
 169  	}
 170  
 171  	function MiscEvent(ev)		//keypress, and mouseover/mouseout/mousedown event on body.  cancel selecting.
 172  	{
 173  		if(ev.type=='mouseout' && !gHovering)
 174  		{
 175  			InfoMSG('-','white','black','white');
 176  		}
 177  		else if(ev.type=='mouseover' && !gHovering)
 178  		{
 179  			InfoMSG('cancel','yellow','red','yellow');
 180  		}
 181  		else //keypress on document or mousedown on body, cancel ops.
 182  		{
 183  			CleanupDOMSelection();
 184  		}
 185  	}
 186  	
 187  	function InfoMSG(text,color,bgcolor,border)
 188  	{
 189  		
 190  		var s=infoDivHover.style;
 191  		if(color)s.color=color;
 192  		if(bgcolor)s.backgroundColor=bgcolor;
 193  		if(border)s.borderColor=border;
 194  		if(text)hoverText.data=text;
 195  	}
 196  	
 197  
 198  
 199  	
 200  	
 201  	//(Section 2) Element Isolation
 202  	function ElementSelected(element)	//finished selecting element.  setup string to prompt user.
 203  	{
 204  		PromptUserXpath(ElementInfo(element));
 205  	}
 206  	
 207  	
 208  	function PromptUserXpath(defaultpath)		//prompt user, isolate element.
 209  	{
 210  		var userpath = prompt("XPath of elements to isolate : ", defaultpath);
 211  		if(userpath && userpath.length>0)
 212  		{
 213  			var addPredicate = "[count(./ancestor-or-self::head)=0][count(./ancestor-or-self::title)=0]";	//exclude head & title elements from selection so they aren't removed
 214  			var addPath = "//script | //form | //object | //embed";	//include these elements in selection for removal
 215  			var pathx=TransformXPath_NoAncestorDescendentSelf(userpath, addPredicate, addPath);		//the xpath selection of all elements to be removed/deleted.
 216  			
 217  			try
 218  			{
 219  				var element;
 220  				var elements=$XPathSelect(pathx);	
 221  				for(var i=0;element=elements(i);i++)
 222  				{			
 223  
 224  					if(!element.nodeName.match(/^(head|title)$/i))	//redundant check.
 225  					{
 226  						ElementRemove(element);
 227  					}
 228  				}
 229  			}
 230  			
 231  			catch(err)
 232  			{
 233  				alert("wtf: "+err);
 234  			}
 235  			
 236  		}
 237  	}
 238  	
 239  		
 240  	
 241  	//support
 242  	function $XPathSelect(p, context) 
 243  	{
 244  	  if (!context) context = document;
 245  	  var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
 246  	  return function(x) { return xpr.snapshotItem(x); };	//closure.  wooot!  returns function-type array of elements (usually elements, or something else depending on the xpath expression).
 247  	}
 248  	
 249  	function ElementRemove(e)
 250  	{
 251  		if(e)e.parentNode.removeChild(e);
 252  	}
 253  	
 254  	function ElementInfo(element)
 255  	{
 256  		var txt='';
 257  		if(element)
 258  		{
 259  			txt=element.tagName.toLowerCase();		//txt=element.tagName;
 260  			txt=attrib(txt,element,'id');
 261  			txt=attrib(txt,element,'class');	
 262  			txt='//'+txt;
 263  		}
 264  		return txt;
 265  		
 266  		function attrib(t,e,a)
 267  		{			
 268  			if(e.hasAttribute(a))
 269  			{
 270  				t+="[@"+a+"='"+e.getAttribute(a)+"']";
 271  			}
 272  			return t;
 273  		}
 274  		
 275  	}
 276  
 277  
 278  	
 279  	//function to 'invert' the XPath by selecting all elements that are not ancestor and not descendent and not self.
 280  	function TransformXPath_NoAncestorDescendentSelf(u, includePredicates, includePaths)
 281  	{	
 282  		
 283  		//sample input (u):					//div[@class='sortbox']
 284  		//sample output						//*[  not(./descendant-or-self::*=//div[@class='sortbox'])][  not(./ancestor-or-self::*=//div[@class='sortbox'])]
 285  		//sample output with additional conditions:		//*[  not(./descendant-or-self::*=//div[@class='sortbox'])][  not(./ancestor-or-self::*=//div[@class='sortbox'])][count(./ancestor-or-self::head)=0][count(./ancestor-or-self::title)=0]
 286  		
 287  			//obsolete method.  much faster but can only be used for limited types of (simple) xpath expressions -- unlike the current version, which should be able to convert any xpath.
 288  			//input:			table[@id='topbar']
 289  			//output:			//*[not(./descendant-or-self::table[@id='topbar']) and not(./ancestor-or-self::table[@id='topbar'])]
 290  			//output (alternative):	//*[count(./descendant-or-self::table[@id='topbar'])=0 and count(./ancestor-or-self::table[@id='topbar'])=0]
 291  		
 292  		
 293  		var o1=	'./descendant-or-self::*='+gr(u);
 294  		o1=	'not' + gr(o1);
 295  		o1=	nt(o1);	
 296  		var o2= './ancestor-or-self::*='+gr(u);
 297  		o2=	'not' + gr(o2);
 298  		o2=	nt(o2);
 299  
 300  		var o=	'//*'+o1+o2;
 301  		if(includePredicates && includePredicates.length>0)	o += includePredicates;
 302  		if(includePaths && includePaths.length>0) o += ' | ' + includePaths;
 303  		return o;
 304  		
 305  		
 306  		function nt(term){return wrap(term,'[]');}	//node test; predicate - enclose with bracket.
 307  		function gr(term){return wrap(term,'()');}	//group - parenthesize.
 308  		function wrap(term, enclosure){return enclosure.charAt(0)+term+enclosure.charAt(1);}
 309  	}	
 310  	
 311  
 312  
 313  	
 314  })();
 315  

HTML/JavaScript - Select list - Add/Remove Options (DOM)

from http://www.mredkj.com/tutorials/tutorial005.html


Overview

* Insert Before Selected - A new option is created and added above the selected option (as determined by selectedIndex). If none are selected, then no option is added.
* Remove Selected - Deletes the selected option (or options) from the list. If no options are selected, no options are deleted.
* Append Last - No matter what is selected, a new option is added at the end.
* Remove Last - No matter what is selected, the last option is deleted from the list.


Explanation

According to DOM Level 1, the following is the syntax for the add and remove methods in HTMLSelectElement:

void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

The add method takes two arguments: the element to add, and the element to insert before. The spec also says you can add to the end of the list by passing null as the second argument.

The remove method just takes a number: the index of the option to be removed.


The JavaScript
   1  
   2  <script language="JavaScript" type="text/javascript">
   3  <!--
   4  var count1 = 0;
   5  var count2 = 0;
   6  
   7  function insertOptionBefore(num)
   8  {
   9    var elSel = document.getElementById('selectX');
  10    if (elSel.selectedIndex >= 0) {
  11      var elOptNew = document.createElement('option');
  12      elOptNew.text = 'Insert' + num;
  13      elOptNew.value = 'insert' + num;
  14      var elOptOld = elSel.options[elSel.selectedIndex];  
  15      try {
  16        elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
  17      }
  18      catch(ex) {
  19        elSel.add(elOptNew, elSel.selectedIndex); // IE only
  20      }
  21    }
  22  }
  23  
  24  function removeOptionSelected()
  25  {
  26    var elSel = document.getElementById('selectX');
  27    var i;
  28    for (i = elSel.length - 1; i>=0; i--) {
  29      if (elSel.options[i].selected) {
  30        elSel.remove(i);
  31      }
  32    }
  33  }
  34  
  35  function appendOptionLast(num)
  36  {
  37    var elOptNew = document.createElement('option');
  38    elOptNew.text = 'Append' + num;
  39    elOptNew.value = 'append' + num;
  40    var elSel = document.getElementById('selectX');
  41  
  42    try {
  43      elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  44    }
  45    catch(ex) {
  46      elSel.add(elOptNew); // IE only
  47    }
  48  }
  49  
  50  function removeOptionLast()
  51  {
  52    var elSel = document.getElementById('selectX');
  53    if (elSel.length > 0)
  54    {
  55      elSel.remove(elSel.length - 1);
  56    }
  57  }
  58  //-->
  59  </script>



The HTML
   1  
   2  <form>
   3  <input type="button" value="o" onclick="insertOptionBefore(count1++);" />
   4  Insert Before Selected<br />
   5  <input type="button" value="o" onclick="removeOptionSelected();" />
   6  Remove Selected<br />
   7  <select id="selectX" size="10" multiple="multiple">
   8  <option value="original1" selected="selected">Orig1</option>
   9  <option value="original2">Orig2</option>
  10  </select>
  11  <br />
  12  <input type="button" value="o" onclick="appendOptionLast(count2++);" />
  13  Append Last<br />
  14  <input type="button" value="o" onclick="removeOptionLast();" />
  15  Remove Last
  16  </form>

Java DOM: Sample XPath Query

   1  
   2      try
   3      {
   4        XPath xpath = XPathFactory.newInstance().newXPath();
   5        Element e = (Element) xpath.evaluate("/Archive/Section/Description", parentNode,
   6            XPathConstants.NODE);
   7        printXmlNode(e);
   8      }
   9      catch (XPathExpressionException e)
  10      {
  11        e.printStackTrace();
  12      }
« Newer Snippets
Older Snippets »
Showing 1-10 of 26 total  RSS