JavaScript改变DIV背景使用ID

JavaScript change DIV background using ID

本文关键字:ID 背景 改变 DIV JavaScript      更新时间:2023-09-26

我有一个<div>它的ID =" 123456"

如果我运行以下命令,我将得到console.log

中显示的123456
dId = obj.id,
console.log(dId);

如果我这样做,我可以改变背景

document.getElementById("123456").style.background="#EEE000";

然而,这失败了"Uncaught TypeError: Cannot read property 'style' of null"

document.getElementById(dId).style.background="#EEE000";

我怎么能做到这一点使用var dId ?

为清晰起见,obj =

<div id="123456" class="drag" style="border-style: solid; cursor: move;">TEST</div>

obj。id = 123456

新工作JFiddle jsfiddle.net/pyefk58z/2当一个项目被拖到下拉区,我如何改变项目的背景颜色,以显示它在下拉列表?

谢谢

只用dId,不用document.getElementById()

另外,你的ID名是无效的CSS语法:http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier

https://jsfiddle.net/ryanpcmcquen/foLxrqrc/

var dId = document.querySelector('#a123456');
console.log(dId);
//document.getElementById("a123456").style.background = "#EEE000";
dId.style.background = "#EEE000";
div {
  width: 100px;
  height: 100px;
}
<div id="a123456"></div>

给定您想要的obj等于什么,这将工作:

https://jsfiddle.net/ryanpcmcquen/ewct9kL3/

var obj = document.querySelector('#a123456');
var dId = obj.id;
console.log(dId);
//document.getElementById("a123456").style.background = "#EEE000";
document.getElementById(dId).style.background = "#EEE000";
div {
  width: 100px;
  height: 100px;
}
<div id="a123456" class="drag" style="border-style: solid; cursor: move;">TEST</div>

我仍然推荐使用我的第一种方法,但要因人而异。

您可以使用dID作为id,您应该检查dId包含正确的id

var obj = {
  id: 123456 // does not matter string or integer
};
var dId = obj.id;
document.getElementById(dId).style.background = "#EEE000";
<div id="123456">
  Test
</div>