javascript issue getElementById to modify CSS

javascript issue getElementById to modify CSS

本文关键字:modify CSS to getElementById issue javascript      更新时间:2023-09-26

我有一个关于getElementById的问题。
以下是导致问题的 JavaScript 代码部分:
var elmt = document.getElementById("cardSlotsJoueur");

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

我想修改这个 (Css):

#cardSlotsJoueur div {

但它实际上修改了#cardSlotsJoueur {

你能帮我找到一种方法来修改第一个 getElementById 吗?

谢谢!

如果你只想用id=cardSlotsJoueur修改元素中的第一个div,你可以使用这个:

var elmt = document.getElementById("cardSlotsJoueur").getElementsByTagName("div")[0];

要针对#cardSlotsJoueur div,最好使用querySelector方法来检索#cardSlotsJoueur容器的子div 元素:

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

如果您希望#cardSlotsJoueur下有多个div元素,那么您需要先将它们全部获取

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

,然后在for循环中将backgroundImage设置为每个。

您需要

#cardSlotsJoueur中找到div元素:

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')"; 
}

执行所需操作的最佳方法可能是使用具有所需样式的类并将其添加到元素中。但作为替代方案,您可以向最后一个样式表添加规则,例如

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")');
}

您可以将其设置为通用:

function addRule(ruleText) {
  var sheets = document.styleSheets;
  if (!sheets.length) {
    document.head.appendChild(document.createElement('style'));
  }
  sheets[sheets.length - 1].insertRule(ruleText);
}

并像这样称呼它:

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