David Garcia
David Garcia

Reputation: 2696

Jquery matching multiple elements with same id/class

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

Answers (2)

Adil
Adil

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.

Live Demo

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

Dan F
Dan F

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

Related Questions