0

In a document, there are 2 elements with the class name "div._13NKt.copyable-text.selectable-text". (It's web.whatsapp.com)

One on top of the document, one on the bottom of the document.

I would like to querySelect the 2nd element / the element on the bottom.

How could I do this?

Is there an option to do a querySelect backwards?

Here is my code so far:

document.querySelector("div._13NKt.copyable-text.selectable-text").focus();

I am running this command using mobileFX web brower based on Chromium.

I call it like this:

webkit1.Eval("document.querySelector(" & Quote("div._13NKt.copyable-text.selectable-text") & ").focus();")
tmighty
  • 10,734
  • 21
  • 104
  • 218
  • 2
    Can you use [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) and take the last result? Per [in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?](https://stackoverflow.com/questions/5684811/in-queryselector-how-to-get-the-first-and-get-the-last-elements-what-traversal) – D M Jan 26 '22 at 16:35
  • https://stackoverflow.com/questions/22902447/how-to-get-the-second-match-with-queryselector Answer to your question in this link – Vitor EL Jan 26 '22 at 16:36
  • Alternatively: `querySelector('div._13NKt.copyable-text.selectable-text:last-child')` per [this answer](https://stackoverflow.com/a/11981476/14956277) on the same question. – D M Jan 26 '22 at 16:38
  • @DM your first hint worked for me: https://stackoverflow.com/questions/5684811/in-queryselector-how-to-get-the-first-and-get-the-last-elements-what-traversal – tmighty Jan 26 '22 at 16:41
  • Thank you very much!! – tmighty Jan 26 '22 at 16:41
  • @DM I like the beauty of the code that you linked to. I would rather use this code than the other answers. – tmighty Jan 26 '22 at 16:44
  • 2
    keep in mind that using the `:last-child` option only works if all the items are direct siblings. If they are in separate parent elements, the first one will still match the last-child selector. – mykaf Jan 26 '22 at 16:47

2 Answers2

1

I think you can use document.querySelectorAll("div._13NKt.copyable-text.selectable-text") and then access to the index.

//Capture the elements
let myVar = document.querySelectorAll("div._13NKt.copyable-text.selectable-text");

//Then access to the index, taking into account that the initial index is 0.
console.log(myVar[1])
//Or
var secObject = myVar[1];
Mateo Guio
  • 131
  • 4
1

Something like this?

const elements = document.querySelectorAll("div._13NKt.copyable-text.selectable-text");
if(elements.length) elements[elements.length - 1].focus();
zbyso
  • 108
  • 5