简体   繁体   English

在javascript中选择element by和classname

[英]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事件,需要动态选择一个ID,然后添加一个预设的类名来传递给一个函数。

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

The equivalent in jquery jquery中的等价物

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

So how do I select an ID+classname in javascript? 那么如何在javascript中选择ID + classname? I know I'm being dense. 我知道我很密集。

You need to use a classname? 你需要使用一个类名吗? Ids should be unique. Ids应该是独一无二的。

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

Or say element is a parent and you want a child with a class 或者说element是父母,你想要一个有孩子的孩子

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. 此代码基本上遍历所有子代,并使用indexOf()来测试您的类的存在。 If it finds it, it pushes it onto the new array. 如果找到它,它会将其推送到新数组。

From http://www.anyexample.com/webdev/javascript/javascript_getelementsbyclass_function.xml 来自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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM