Reputation: 4430
Any number of elements can exist, with the following 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.
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);
}
}
Upvotes: 1
Views: 7481
Reputation: 5625
You can reference the element directly like so:
Non jQuery method:
var myNum = 3;
var el = document.getElementById('my-div-' + myNum);
if (!el) {
alert("Fail");
} else {
alert("Success");
}
Working example: http://jsfiddle.net/EtZxh/4/
jQuery Method:
If you want to use jQuery simply replace with the following:
var myNum = 5;
var el = $('#my-div-' + myNum);
if (el.size() == 0) {
alert("Fail");
} else {
alert("Success");
}
Working example: http://jsfiddle.net/EtZxh/
Upvotes: 4
Reputation: 44740
You can do something like this in 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)
}
});
Upvotes: 0
Reputation: 4885
var myNum = 3;
$('div[id^="my-div-"]').each(function() {
console.log("hello");
if(myNum === parseInt($(this).attr('id').replace('my-div-',''), 10)) {
alert("found => " + $(this).attr('id'));
} else {
// do else
}
});
Upvotes: 0
Reputation: 83
Using jQuery you could select it with the following:
var id = 4;
var $element = $("#my-div-" + id);
Where id is the variable that holds the number.
Upvotes: 6
Reputation: 298582
getElementById
doesn't return multiple elements. It returns only one:
var elem = document.getElementById('my-div-' + number);
if (elem) {
// elem exists
}
And jQuery:
if ($('#my-div-' + number).length > 0) {
// elem exists
}
Upvotes: 1