[英]Loop through elements to find specific ID
Any number of elements can exist, with the following ID. 可以存在具有以下ID的任意数量的元素。
<div id="my-div-1">Title 1</div>
<div id="my-div-2">Title 2</div>
<div id="my-div-3">Title 3</div>
<div id="my-div-4">Title 4</div>
I would like to loop through those elements to see if the number at the end of the ID matches the number in a variable. 我想遍历这些元素,以查看ID末尾的数字是否与变量中的数字匹配。
This is what I have so far thought it does not work: 到目前为止,我一直认为这是行不通的:
var myNum = 3
var findNum = /[\d]+/;
var findElement = document.getElementById('my-div-' + findNum);
for(i=0; i<findElement; i++) {
if (myNum = findNum) {
console.log('Success! myNum = ' + myNum +
' and findNum = ' + findNum +
' and findElement = ' + findElement);
}
else {
console.log('Fail! myNum = ' + myNum +
' and findNum = ' + findNum +
' and findElement = ' + findElement);
}
}
Using jQuery you could select it with the following: 使用jQuery,您可以通过以下方式选择它:
var id = 4;
var $element = $("#my-div-" + id);
Where id is the variable that holds the number. 其中id是保存数字的变量。
You can reference the element directly like so: 您可以像这样直接引用元素:
Non jQuery method: 非jQuery方法:
var myNum = 3;
var el = document.getElementById('my-div-' + myNum);
if (!el) {
alert("Fail");
} else {
alert("Success");
}
Working example: http://jsfiddle.net/EtZxh/4/ 工作示例: http : //jsfiddle.net/EtZxh/4/
jQuery Method: jQuery方法:
If you want to use jQuery simply replace with the following: 如果要使用jQuery,只需将以下内容替换为:
var myNum = 5;
var el = $('#my-div-' + myNum);
if (el.size() == 0) {
alert("Fail");
} else {
alert("Success");
}
Working example: http://jsfiddle.net/EtZxh/ 工作示例: http : //jsfiddle.net/EtZxh/
getElementById
doesn't return multiple elements. getElementById
不返回多个元素。 It returns only one: 它仅返回一个:
var elem = document.getElementById('my-div-' + number);
if (elem) {
// elem exists
}
And jQuery: 和jQuery:
if ($('#my-div-' + number).length > 0) {
// elem exists
}
You can do something like this in jQuery 您可以在jQuery中执行类似的操作
var num = 3;
$("div[id^='my-div-']").each(function(){
var id = this.id;
if(id.slice(-1) === num){
alert("Success: " +id);
}else{
alert("Fail : " +id)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.