开发者

Select element by and classname in javascript

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开发者_如何学C I'm being dense.


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 + ' ').indexOf(' yourClassName ') > -1) {
         newElements.push(elements[i]);
    }
}

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


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'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜