0

I am trying to add a background image to each element on my page. The background images name is same as the id of the page (without the.png)

for example:

<div class="ClassOne" id='1'> /* i want this to have a bg of:  background-image:url('1.png')*/
</div>
<div class="ClassOne" id='2'> /* i want this to have a bg of:  background-image:url('2.png')*/
</div>
<div class="ClassOne" id='3'> /* i want this to have a bg of:  background-image:url('3.png')*/
</div>
user243405
  • 83
  • 7
  • 1
    Check this for ids with numbers http://stackoverflow.com/questions/5672903/can-i-have-a-div-with-id-as-number – web-tiki May 30 '14 at 11:05

3 Answers3

1

Do you have a set number of possibilities? If you do you could use CSS:

#1 {
    background-image: url('1.png');
}

Now the element with an id of 1 will have that background image.

If you have multiple/more dynamic ids you might consider a javascript solution along the lines of: (edit: tailored to suit your comment)

function setBackgroundFromId(targetEl) {
    targetEl.style.backgroundImage('url(' + targetEl.id + '.png');
}
var imageDivs = document.querySelectorAll('ClassOne');
for (var i = 0; i < imageDivs.length; i++) {
    setBackgroundFromId(imageDivs[i]);
}
Samih
  • 1,078
  • 9
  • 15
1

Try this with jQuery.

Code Modified

var element = $(".ClassOne");
for(var i=0; i<element.length; i++)
{
 var id = element.eq(i).attr("id");
 element.eq(i).css({
  "background": "url("+ id +".png)"
 });
}
Mayank Tripathi
  • 1,346
  • 7
  • 21
0

Can't you just add the attribute:

style="background-image:url('x.png')"

To each element in the same way you generated the id attributes?

Andres
  • 13
  • 4