Home > Mobile >  Why doesn't my className selector return an element?
Why doesn't my className selector return an element?

Time:01-26

With this code, I get into the class "v1Nh3 kIKUG _bz0w" , so basically first_pic.className equals "v1Nh3 kIKUG _bz0w". I get the same result by using the line which I have commented out. But now how can I use this to get the href link (I marked it blue in the picture below) and print it out with window.alert?

var x = document.getElementsByClassName("SCxLW  o64aR ")[0].children;
var x_in = x[0].children;
var x_in_in = x_in[3].children;
//window.alert(document.querySelector("main.SCxLW.o64aR article div div div div").className);
var first_pic = x_in_in[0].children[0].children[0].children[0].children[0];
window.alert(first_pic.href);

enter image description here

CodePudding user response:

Since you cannot rely on the changing classes, you should focus on the tag names.

I would try this:

let link = document.querySelector("main article:nth-child(1) a")
console.log(link.href)

EDIT

Another thing to try would be to focus on something unique and "stable"... like the tabindex attribute:

let link = document.querySelector("[tabindex='0']")
console.log(link.href)

Another EDIT (answer to OP comment under his question)

If someone has a working solution that is not using qerySelector but something else...

If the link is the very first of the article, this would work:

let article = document.getElementsByTagName("article")[0]
let link = article.getElementsByTagName("a")[0]
console.log(link.href)
  •  Tags:  
  • Related