在下拉列表中,我想从选项元素中获取自定义属性:
<select name="t" id="t">
<option value="all">- all -</option>
<optgroup label="Europe">
<option selected value="1" myAttr="1">Fr</option>
<option value="2" myAttr="0">Uk</option>
</optgroup>
<optgroup label="America">
<option value="3" myAttr="1">USA</option>
<option value="4" myAttr="0">CA</option>
</optgroup>
<optgroup label="Asia">
<option value="5" myAttr="0">JP</option>
</optgroup>
</select>
因此,我首先循环遍历 optgroup
标记,然后循环遍历 option
标记 ( Fiddle )。
var temp = document.getElementById("t").childNodes;
// Loop the optGroup
for (var i = 0; i < temp.length; i++) {
// Loop the option
for (var j = 0; j < temp[i].childNodes.length; j++) {
然后我想在获取自定义属性之前测试我的元素是否是 HTMLOptionElement,我尝试了 this SO question 中的一些提示,但如果没有成功,我总是得到“未定义”。这是与 DOM 元素一起使用的特定方法吗?
最佳答案
您需要使用nodeName :
var div1 = document.getElementById("d1");
var div1Type = div1.nodeName;
和 nodeName and tagName 之间的区别.
关于javascript - 如何获取 DOM 元素的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24240474/