I want reach the area which I have marked blue and print the name of this class (Nnq7C weEfm). I have started from the "main class" and made it into the class called ySN3v like this:
var x = document.getElementsByClassName("SCxLW o64aR ")[0].children;
var x_in = x[0].children;
var x_in_in = x_in[3].children;
window.alert(x_in_in[0].className);
Which gives me the name of class ySN3v as output. I see no way reaching the blue area and alerting out the name of this class ("Nnq7C weEfm") like this, how can this be done?
If my question is not clear please let me know! :)
CodePudding user response:
I would give document.querySelector a try, it should make life considerably easier.
const yourDiv = document.querySelector("main.SCxLW.o64aR article div div div");
console.log(yourDiv.className);
<main >
<div>
<div>
<article>
<div>
<div>
<div >
</div>
</div>
</div>
</article>
</div>
</div>
</main>
CodePudding user response:
If you want to get the class name of the blue selection and all it's siblings, you can use document.querySelectorAll:
// Get target and all it's siblings
const targetElements = document.querySelectorAll('main article > div > *');
// The a list of unique class names
if (targetElements.length) {
const classNames = [...new Set(
[...targetElements].map(({ className }) => className)
)];
console.log(classNames);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Class Name Example</title>
</head>
<body>
<main>
<div>
<header></header>
<div></div>
<div></div>
<div>
<article>
<div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
</article>
</div>
</div>
</main>
</body>
</html>

