在javascript中选择元素和类名 [英] Select element by and classname in javascript

查看:93
本文介绍了在javascript中选择元素和类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个onChange事件需要动态地选择一个ID,然后添加一个预设的类名来传递给一个函数。

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

jquery中的等价物

  $( '#' + THIS.VALUE + 'myclassname。')()的函数。 

那么如何在javascript中选择一个ID +类名?我知道我很密集。

解决方案

你需要使用一个类名? Ids应该是唯一的。

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

或说元素是父母,你想要一个类的孩子

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

var newElements = [];对于(var i = 0,length = elements.length; i< length; i ++){

if((''+ elements [i] .className + '').indexOf('yourClassName')> -1){
newElements.push(elements [i]);
}
}

这段代码基本上遍历所有的孩子,并使用 indexOf()来测试你的类的存在。如果它找到它,它将它推送到新的数组。


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.

解决方案

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.

这篇关于在javascript中选择元素和类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆