gooser
gooser

Reputation: 306

Apply Same CSS to multiple ID's using Jquery

I need an html structure that looks like this:

<div id="ABTestBanner_New">
</div>

<div id="ABTestBanner_Fav">
</div>

<div id="ABTestBanner_Budget">
</div>

I need to use it in an AB split test. So I need to write in javaScript, and I need all three divs to be unique id's but have the same CSS. I tried to do it this way but only the #ABTestBanner_Budget is getting the CSS applied:

var $divNew = $('<div></div>', {'id': 'ABTestBanner_New'});
$('div.samplesCell.samples1').after($divNew)

var $divFav = $('<div></div>', {'id': 'ABTestBanner_Fav'});
$($divNew).after($divFav);

var $divBudget = $('<div></div>', {'id': 'ABTestBanner_Budget'});
$($divFav).after($divBudget);

$('#ABTestBanner_New' && '#ABTestBanner_Fav' && '#ABTestBanner_Budget').css({
    float : 'left',
    height : '250px',
    width : '950px',
    backgroundColor:'#0080FF',
    margin:'20px 0px 20px 0px'
});

Any thoughts on what I am doing wrong?

Upvotes: 3

Views: 7837

Answers (4)

Waterskier19
Waterskier19

Reputation: 136

Why don't you just add a class to those elements and style the class the way you want to?

$ABTestBanner_New.addClass("foo");
$ABTestBanner_Fav.addClass("foo");
$ABTestBanner_Budget.addClass("foo");

Adding/Removing a class is a little more efficient than adding inline styles on the fly, it also helps to keep all your styles in the CSS file where they belong. :-)

Upvotes: 1

Arbel
Arbel

Reputation: 30989

Simply use:

$('div[id^="ABTestBanner"]').css({
    /* styles */
});

DEMO: http://jsfiddle.net/rw53Q/

The div[id^="ABTestBanner"] selector targets all div elements whose id start with ABTestBanner.

Upvotes: 2

maximkou
maximkou

Reputation: 5332

See jquery docs here: http://api.jquery.com/category/selectors/

$('#ABTestBanner_New, #ABTestBanner_Fav, #ABTestBanner_Budget').css({
    /*your style*/
});

Upvotes: 11

SamotnyPocitac
SamotnyPocitac

Reputation: 402

$('#ABTestBanner_New , #ABTestBanner_Fav , #ABTestBanner_Budget').css({
    float : 'left',
    height : '250px',
    width : '950px',
    backgroundColor:'#0080FF',
    margin:'20px 0px 20px 0px'
});

instead of && use comma

Upvotes: 0

Related Questions