Javascript按选择类获取元素

时间:2017-06-22 08:14:23

标签: javascript jquery

 <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"看到第一个代码示例的第一行?谢谢:))

2 个答案:

答案 0 :(得分:4)

使用 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")

答案 1 :(得分:-1)

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

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

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