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 11-20 of 23 total

Java - Dom Parser Example

// Simple Parser XML with DOM

package parser;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMParser
{
	private Document doc = null;
	
	public DOMParser()
	{
		try
		{
			doc = parserXML(new File("parser/file.xml"));
			
			visit(doc, 0);
		}
		catch(Exception error)
		{
			error.printStackTrace();
		}
	}
	
	public void visit(Node node, int level)
	{
		NodeList nl = node.getChildNodes();
		
		for(int i=0, cnt=nl.getLength(); i<cnt; i++)
		{
			System.out.println("["+nl.item(i)+"]");
			
			visit(nl.item(i), level+1);
		}
	}
	
	public Document parserXML(File file) throws SAXException, IOException, ParserConfigurationException
	{
		return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
	}
	
	public static void main(String[] args)
	{
		new DOMParser();
	}
}

Add Rows to an HTML table Dynamically

// description of your code here
This script modifies an existing table in a page using
the DOM methods to add rows

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<script type="text/javascript">
function addRow(content,morecontent)
{
         if (!document.getElementsByTagName) return;
         tabBody=document.getElementsByTagName("TBODY").item(0);
         row=document.createElement("TR");
         cell1 = document.createElement("TD");
         cell2 = document.createElement("TD");
         textnode1=document.createTextNode(content);
         textnode2=document.createTextNode(morecontent);
         cell1.appendChild(textnode1);
         cell2.appendChild(textnode2);
         row.appendChild(cell1);
         row.appendChild(cell2);
         tabBody.appendChild(row);
       
   
}
</script>
</head>
<body>
<table border='1' id='mytable'>
<tbody>
<tr><td>22</td><td>333</td></tr>
<tr><td>22</td><td>333</td></tr>
</tbody>
</table>
<button onClick='addRow("123","456");return false;'>
Add Row</button>
</body>
</html>

javascript window event handling manager

I've seen a lot of window.onload managers, so I generalized it for any window event handler. This assumes prototype.
// BurntoEventManager
// http://brentfitzgerald.com/
// January 2007

var BurntoEventManager = {
    handlers: {},
    add: function(handler_name, method) {
        if(this.handlers[handler_name] == null) {
            this.handlers[handler_name] = new Array();
        }
        this.handlers[handler_name].push(method);
        
        // Now update the window event handler
        window[handler_name] = function(evt) {
            this.handlers[handler_name].each(function(m) {
                m(evt);
            }.bind(this));
        }.bind(this);
    },
    
    clear: function(handler_name) {
        this.handlers[handler_name] = null;
        window[handler_name] = function() {};
    },
    
    get: function(handler_name) {
        return this.handlers[handler_name];
    }
}

For example, consider if later on in our application we want to add an onclick handler.
BurntoEventManager.add("onclick", function(evt) { alert(evt) });

get size of scrollbar

// description of your code here
from http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels

function getScrollerWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}

Cross-browser way to retrieve styles for elements via the DOM

document.getElementById('whatever').style only gives local styles, but if you want those specified in external CSS definitions, you have to arse about (why, oh, why?) and do it like this:

function newGetStyle(nodeName, sStyle) {
	var x = document.getElementById(nodeName);
	var y;
	if (x.currentStyle) {
		y = x.currentStyle[sStyle];
	} else {
		try {
		y = document.defaultView.getComputedStyle(x,null).getPropertyValue(sStyle);
	  } catch(e) { }
	}
	return y;
}

Simple Javascript/XML based search

// Use javascript to search an XML based index.
// Provides simple site search where no server-side
// alternatives are available (for example: on a CD ROM)

// The sample XML:
<?xml version="1.0" encoding="utf-8"?>
<searchable_index>
	<item>John</item>
	<item>Paul</item>
	<item>George</item>
	<item>Ringo</item>
</searchable_index>


// The javascript:
window.onload = loadIndex;

function loadIndex() { // load indexfile
// most current browsers support document.implementation
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.load("index.xml");
	}
// MSIE uses ActiveX
	else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.load("index.xml");
	}
}


function searchIndex() { // search the index (duh!)
	if (!xmlDoc) {
		loadIndex();
	}
	// get the search term from a form field with id 'searchme'

	var searchterm = document.getElementById("searchme").value;
	var allitems = xmlDoc.getElementsByTagName("item");
	results = new Array;
	if (searchterm.length < 3) {
		alert("Enter at least three characters");
	} else {
		for (var i=0;i<allitems.length;i++) {
// see if the XML entry matches the search term,
// and (if so) store it in an array
			var name = allitems[i].lastChild.nodeValue;
			var exp = new RegExp(searchterm,"i");
			if ( name.match(exp) != null) {
				results.push(allitems[i]);
			}
		}
// send the results to another function that displays them to the user
	showResults(results, searchterm);
	}
}


// The following is just an example of how you
// could handle the search results
function showResults(results, searchterm) {

	if (results.length > 0) {
// if there are any results, put them in a list inside the "resultshere" div
		var resultshere = document.getElementById("resultshere");
		var header = document.createElement("h5");
		var list = document.createElement("ul");
		var searchedfor = document.createTextNode("You've searched for "+searchterm);
		resultshere.appendChild(header);
		header.appendChild(searchedfor);
		resultshere.appendChild(list);
		for (var i=0;i<results.length;i++) {
			var listitem = document.createElement("li");
			var item = document.createTextNode(results[i].lastChild.nodeValue);
			list.appendChild(listitem);
			listitem.appendChild(item);
		}
	} else {
// else tell the user no matches were found
		var resultshere = document.getElementById("resultshere");
		var para = document.createElement("p");
		var notfound = document.createTextNode("Sorry, I couldn't find anything like "+searchterm +"!");
		resultshere.appendChild(para);
		para.appendChild(notfound);
	}
}


// Here's some s(a|i)mple HTML that should work with the code above:

<html>
<head>
<script type="text/javascript" src="searchindex.js"></script>
</head>
<body>
<form action="">
<input type="text" id="searchme" />
<input type="submit" onclick="searchIndex(); return false;" />
</form>
<div id="resultshere">
</div>
</body>
</html>

change title with javascript

// change title with javascript

..
<title>original title</title>
..
<script type="text/javascript">
function changeTitle(title) { document.title = title; }
</script>
..
<input type='button' onclick='changeTitle("new title")' value='Change Title'/> 
..

change text

// javascript to change text

<script type="text/javascript">
function changeText(txt){
	document.getElementById('the_text').innerHTML = txt;
}
</script>
<p>Hello <b id='name'>World</b>. </p>
<input type='button' onclick='changeText("Oliver")' value='Change Text'/>

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>
« Newer Snippets
Older Snippets »
Showing 11-20 of 23 total