Reputation: 2696
I am working on showing a message when a particular element has a width of less than 50, however there are multiple elements with the same class and only the first element in the page is displaying the message. here is the jsfiddle http://jsfiddle.net/MaNdn/23/
Here is the function.
function checkads() {
if ($('#container').height() < 50) {
$('#container').parent().parent().prepend('<div id="ad-notice">Please support our website</div>');
//
}
}
$(document).ready(checkads);
My question is, how do you make the message prepend to all element id instances found. I have various advertisements around my website, they are all wrapped in an div element named advertisement_container
then how do I match them all at once
Upvotes: 2
Views: 20135
Reputation: 148120
You need to use each() to iterate through the matched element. Instead of using same id for multiple elements use the same class as the id of element is supposed to be unique. To select multiple elements with same class you can use attribute selector like $('[id=container]') but it is better to use class and keep the ids of elements unique.
function checkads() {
$('.someclass').each(function(){
if($(this).height() < 50) {
$(this).parent().parent().prepend('<div id="ad-notice">Please support our website</div>');
}
});
}
$(document).ready(checkads);
Upvotes: 7
Reputation: 12052
ID has to be unique. Change it to be a class, not an ID, then you can use filter and something like
function checkads() {
$('.container').filter(function (index) {
return $(this).height() < 50;
}).parent().parent().prepend('<div id="ad-notice">Please support our website</div>');
}
Upvotes: 1