views:

38

answers:

2

I have an onChange event that needs to dynamically select an ID and then add a preset classname to pass to a function.

onChange = "show(document.getElementById(this.value). {select a class here? } );"

The equivalent in jquery

$('#'+this.value+'.myclassname').function();

So how do I select an ID+classname in javascript? I know I'm being dense.

A: 

From http://www.anyexample.com/webdev/javascript/javascript_getelementsbyclass_function.xml

function getElementsByClass( searchClass, domNode, tagName) { 
    if (domNode == null) domNode = document;
    if (tagName == null) tagName = '*';
    var el = new Array();
    var tags = domNode.getElementsByTagName(tagName);
    var tcl = " "+searchClass+" ";
    for(i=0,j=0; i<tags.length; i++) { 
        var test = " " + tags[i].className + " ";
        if (test.indexOf(tcl) != -1) 
            el[j++] = tags[i];
    } 
    return el;
} 
getElementsByClass('center', document.getElementById('content'))
armonge
+3  A: 

You need to use a classname? Ids should be unique.

var element = document.getElementById('myId');

Or say element is a parent and you want a child with a class

var elements = element.getElementsByTagName('*');

var newElements = [];

for (var i = 0, length = elements.length; i < length; i++) {

    if (elements[i].className.match(/yourClassName/)) {
         newElements.push(elements[i]);
    }
}

This code basically walks through all children, and uses regex to test for the presence of your class. If it finds it, it pushes it onto the new array.

If you can't use a regex literal (perhaps you want to specify the class name as an argument), then you need to use new Regex().

alex