繁体   English   中英

Javascript按选择类获取元素

[英]Javascript get element by select class

 <select class="tmcp-field tillagg-width tm-epo-field tmcp-select"
                name="tmcp_select_30"
                data-price=""
                data-rules="" 
                data-original-rules=""                 
                id="tmcp_select_75"
                tabindex="75">
            <option  value="5 (480 mm)_0" etc.......

为了获得这个元素的价值,目前我正在使用这段代码:

document.getElementById("tmcp_select_75").value

它工作得很好,但是如何使用"tmcp-field tillagg-width tm-epo-field tmcp-select"获得元素的值?看到它的第一个代码示例的顶行? 谢谢 :)

使用 querySelector()querySelectorAll()getElementsByClassName()

// Gets the first match's
document.querySelector(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")

// Gets a collection of the selects;
document.querySelectorAll(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")

// Gets a collection of the selects;
document.getElementsByClassName("tmcp-field tillagg-width tm-epo-field tmcp-select")

jQuery的

$(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")

你不需要jQuery。 如果我正确地读你,你想要使用它的类而不是ID来选择元素,就像你现在正在做的那样。 使用document.querySelector:

document.querySelector('.tmcp-field.tillagg-width.tm-epo-field.tmcp-select');

您可能不需要为所有这些类选择,因此请删除任何不需要缩小结果范围的类。

暂无
暂无

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

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