简体   繁体   English

如何使用 DOM JavaScript 检测元素?

[英]How to detect element with DOM JavaScript?

I want to detect an element and change the backgroundColor through JavaScript but am having trouble with it.我想检测一个元素并通过 JavaScript 更改背景颜色,但遇到了问题。

I can't check for the element because it is a tag+class + tag+class...我无法检查元素,因为它是标签+类+标签+类...

Here's my code :这是我的代码:

var one = document.getElementsByTagName("div");
var two = document.getElementsByClassName("red");
var three = document.getElementsByTagName("h2");
var four = document.getElementsByClassName("title");
one.two three.four.style.backgroundColor ="#00c497";

The format is "div.red h2.title".格式为“div.red h2.title”。

How can I correctly detect an element using DOM JavaScript?如何使用 DOM JavaScript 正确检测元素?

If you can, use querySelector for this:如果可以,请为此使用querySelector

 document.querySelector("div.red h2.title").style.backgroundColor = "#00c497";
 <div> <h2>Don't Touch</h2> </div> <div class="red"> <h2>Don't Touch</h2> <h2 class="title">Change</h2> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM