getElementsByClass(searchClass,node,tag)
A quick and elegant way of grabbing elements by a className by Dustin Diaz
Supply a class name as a string.
(optional) Supply a node. This can be obtained by getElementById, or simply by just throwing in document (it will be document if dont supply a node)). Its mainly useful if you know your parent and you dont want to loop through the entire D.O.M.
(optional) Limit your results by adding a tagName. Very useful when youre toggling checkboxes and etcetera. You could just supply input.
function getElementsByClass(searchClass,node,tag) { var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; }
Here is a sample useage:
<html> <head> <title>getElementsByClass</title> <script type="text/javascript"> <!-- function showFoo() { var el = getElementsByClass(document,'foo','*'); alert(el.length); } //--> </script> </head> <body> <div id="wrapper"> <div> <p>Searching <span class="foo">foo</span></p> <p class="foo">foo</p> <p class="bar Foo">boo Far</p> <p class="bar foo">boo far</p> <p class="foo bar">foo bar</p> <p class="fooo">fooo</p> <p class="foobar">foobar</p> <p class="bar foo bars">bar foo bars</p> <p class="boofar">boofar</p> <button onclick="showFoo();">Show Total foo</button> </div> </body>
Pushing the button shows "5"
See also:
file: /Techref/inet/iis/jscript/htm/getElementsByClass.htm, 2KB, , updated: 2005/12/9 15:41, local time: 2024/11/25 14:04,
3.149.250.65:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://sxlist.com/techref/inet/iis/jscript/htm/getElementsByClass.htm"> JScript / JavaScript Extension Feature</A> |
Did you find what you needed? |
Welcome to sxlist.com!sales, advertizing, & kind contributors just like you! Please don't rip/copy (here's why Copies of the site on CD are available at minimal cost. |
Welcome to sxlist.com! |
.