Select element by and classname in javascript

我们两清 提交于 2019-12-04 05:19:36

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3887619/select-element-by-and-classname-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!