2

I have an issue about getElementById.
Here is the part of the javascript code that causes a problem:
var elmt = document.getElementById("cardSlotsJoueur");

elmt.style.backgroundImage = "url('images/backcard.png')";

I wanted to modify this (Css) :

#cardSlotsJoueur div {

But it actually modifies #cardSlotsJoueur {

Could you help me to find a way to modify the first one with getElementById ?

Thanks !

1
  • You can add an ID to the element you want to change, or you can add a CSS rule to a style sheet that uses an appropriate selector. Commented Jan 2, 2015 at 21:16

4 Answers 4

2

If you only want to modify the first div within the element with id=cardSlotsJoueur, you can use this:

var elmt = document.getElementById("cardSlotsJoueur").getElementsByTagName("div")[0];
Sign up to request clarification or add additional context in comments.

Comments

1

To target #cardSlotsJoueur div it's better to use querySelector method which would retrieve children div element of the #cardSlotsJoueur container:

var elmt = document.querySelector("#cardSlotsJoueur div");

If you expect multiple div elements under the #cardSlotsJoueur then you need to get them all first

var elmt = document.querySelectorAll("#cardSlotsJoueur div");

and then set backgroundImage to each in the for loop.

1 Comment

Thanks for your rapidity ! It works. By the way do you know how to resize the picture that will be in the backgound ?
1

You need to find div elements within #cardSlotsJoueur:

var elmt = document.getElementById("cardSlotsJoueur");
var divs = elmt.getElementsByTagName('div');

for (var i = 0; i < divs.length; i++) { 
  divs[i].style.backgroundImage = "url('images/backcard.png')"; 
}

Comments

0

Probably the best way to do what you want is to use a class with the required styling and add it to the element. But as an alternative, you can add a rule to the last style sheet, e.g.

function addBackground() {
  var sheets = document.styleSheets;

  // If there are no style sheets, add one
  if (!sheets.length) {
    document.head.appendChild(document.createElement('style'));
  }

  // The sheets collection is live, if a new sheet was needed, it's automatically a member
  sheets[sheets.length - 1].insertRule('#cardSlotsJoueur div{background-image:url("images/backcard.png")');
}

You can make it generic:

function addRule(ruleText) {
  var sheets = document.styleSheets;

  if (!sheets.length) {
    document.head.appendChild(document.createElement('style'));
  }

  sheets[sheets.length - 1].insertRule(ruleText);
}

and call it like:

addRule('#cardSlotsJoueur div{background-image:url("images/backcard.png")');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.