Tag Archive for DOM

Javascript DOM – getElementsByClassName

getElementsByClassName: function(classname, baseNode, tag) {
	baseNode = baseNode || document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('b' + classname + 'b');
	var els = baseNode.getElementsByTagName(tag || "*");
	for (var i = 0, j = els.length; i < j; i++)
		if (re.test(els[i].className)) a.push(els[i]);
	return a;
}

source

DOM Parser demo using DocumentBuilder.

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

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

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


public class DocumentBuilderDemo {

	
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilder db = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		db = dbf.newDocumentBuilder();
		Document doc = db.parse(new File("c:simple.xml"));
		
		Element root = doc.getDocumentElement();
		System.out.println(root.getNodeName());
		
		System.out.println("========================================================================");
		
		NodeList nodeList = root.getElementsByTagName("to");
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i).getFirstChild();
			System.out.println(node.getNodeValue());
		}
		
		System.out.println("========================================================================");
		
		nodeList = root.getElementsByTagName("from");
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i).getFirstChild();
			System.out.println(node.getNodeValue());
		}
		
		System.out.println("========================================================================");
		
		nodeList = root.getElementsByTagName("body");
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i).getFirstChild();
			System.out.println(node.getNodeValue());
		}
	
		System.out.println("========================================================================");
	
		
	}

}


/*
The simple.xml file that we used for parsing in above example.


<?xml version="1.0"?>
<msg>
	<note>
		<to>Tom</to>
		<from>Prince</from>
		<heading>Reminder</heading>
		<body>Hello how are u?</body>
	</note>
	<note>
		<to>Sania</to>
		<from>Prince</from>
		<heading>Joking</heading>
		<body>Welcome!!!</body>
	</note>
</msg>

*/

source

SimpleSelector, Javascript DOM selector

/*!
 * $imple$elector
 *
 * Selector by id, className or tagName, f.e.:
 * $$( '#wrap' ) or $$( '.special' ) or $$( 'p' )
 *
 * Mulitple selectors seperated by comma, f.e.:
 * $$( '#id, .cls' )
 *
 * Give context as second param, f.e.:
 * $$( 'a', '#wrap' ) or $$( 'a', wrapNode ) or $$( 'a', [node1, node2] )
 *
 * @version   0.2
 * @author    Victor Villaverde Laan
 * @link      <a href="http://www.freelancephp.net/simpleselector-javascript-dom-selector/" >http://www.freelancephp.net/simpleselector-javascript-dom-selector/</a>
 * @license   MIT license
 */
var SimpleSelector = {

	/**
	 * Find elements with the given selector within the context
	 * @param selector [string]
	 * @param context  [string | DOM node | array of DOM nodes]
	 * @return [DOM node | array of DOM nodes | empty array]
	 */
	find: function ( selector, context ) {
		var selectors = selector.split( ',' ),
			elements = [],
			wrappers = [];

		// set wrappers
		if ( typeof context == 'string' ) {
			var wraps = SimpleSelector.find( context );
			// set array to wrappers
			wrappers = ( wraps.constructor == Array ) ? wraps : [ wraps ];
		} else if ( context && context.constructor == Array ) {
			wrappers = context;
		} else {
			// document is default context
			wrappers.push( context || document );
		}

		// find matching elements within the wrappers (context)
		for ( var a = 0, b = wrappers.length; a < b; a++ ) {
			for ( var x = 0, y = selectors.length; x < y; x++ ) {
				// selector: trim spaces
				var s = selectors[x].replace( / /g, '' ),
					// get operator
					operator = s.substr( 0, 1 ),
					// get key
					key = s.substr( 1 ),
					els = [];

				// get matching elements
				if ( operator == '#' ) {
					// get element by id
					els[0] = document.getElementById( key );
					// check if element is part of context
					if ( els[0] && SimpleSelector.isDescendant( els[0], wrappers[ a ] ) )
						elements.push( els[0] );
				} else if ( operator == '.' ) {
					// get element by className
					els = SimpleSelector.getByClass( key, wrappers[ a ] );
					// convert type to array
					els = [].slice.call( els, 0 );
					// add to elements collection
					elements = elements.concat( els );
				} else {
					// get element by tagName
					els = wrappers[ a ].getElementsByTagName( s );
					// add to elements collection
					// in this case [].slice.call( els, 0 ) does not work
					// in IE, says constructor is undefined??
					for ( var i = 0, j = els.length; i < j; i++ )
						elements.push( els[ i ] );
				}
			}
		}

		// return single element or array of elements
		return ( elements.length == 1 ) ? elements[0] : elements;
	},

	/**
	 * Check wether an element is a descendant of the given ancestor
	 * @param descendant [DOM node]
	 * @param ancestor   [DOM node]
	 * @return [boolean]
	 */
	isDescendant: function ( descendant, ancestor ) {
		return ( ( descendant.parentNode == ancestor )
					|| ( descendant.parentNode != document )
				&& arguments.callee( descendant.parentNode, ancestor ) );
	},

	/**
	 * Cross browser function for getting elements by className
	 * @param className [string]
	 * @param context   [DOM node]
	 * @return [array of DOM nodes]
	 */
	getByClass: function ( className, context ) {
		var elements = [],
			expr = new RegExp('b' + className + 'b'),
			wrapper = context || document,
			allElements = wrapper.getElementsByTagName( '*' );

		// filter all elements that contain the given className
		for ( var x = 0, y = allElements.length; x < y; x++ ) {
			if ( expr.test( allElements[ x ].className ) )
				elements.push( allElements[ x ] );
		}

		return elements;
	}

};

// if global $$ is not set
if ( ! window.$$ )
	window.$$ = SimpleSelector.find;

source

Javascript DOM – Create Element

var root = document.getElementById("root");

var a = document.createElement("a");
a.setAttribute("href", "<a href="http://foobar.com");" >http://foobar.com");</a>
a.setAttribute("title", "Foo Bar");

root.appendChild(a);

source

YUI – Determine when the DOM is ready to be used

<script type="text/javascript">
  // Remember to include:    .../build/yahoo-dom-event/yahoo-dom-event.js
  YAHOO.example.init = function()
  {
    // Init stuff Here
    var myAutoComp = new YAHOO.widget.AutoComplete("myInput","myContainer", myDataSource);
  };
  YAHOO.util.Event.onDOMReady(YAHOO.example.init);
</script>

source

DOMElement outerHTML

<?php

function outerHTML($e) {
	$doc = new DOMDocument();
	$doc->appendChild($doc->importNode($e, true));
	return $doc->saveHTML();
}

?>

source

Easy scraping and HTML parsing with PHP5 and XPath

<?php
//a URL you want to retrieve
$my_url = '<a href="http://www.digg.com';" >http://www.digg.com';</a>
$html = file_get_contents($my_url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

//Put your XPath Query here
$my_xpath_query = "/html/body/div[@id='container']/div[@id='contents']/div[@class='list' and @id='wrapper']/div[@class='main' and position()=1]/div[contains(@class, 'news-summary')]/div[@class='news-body']/h3";
$result_rows = $xpath->query($my_xpath_query);

//here we loop through our results (a DOMDocument Object)
foreach ($result_rows as $result_object){
	echo $result_object->childNodes->item(0)->nodeValue;
}
?>

source

JavaScript Include

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

source

jQuery on Dom ready

$(document).ready(function() {
//put all your jQuery goodness in here.
});

source

Match Elements Even When DOM Changes

$('.myClassToMatchAgainst').livequery(function(event) {
//do this
});

source