V
V
Vladislav2019-11-22 03:46:22
JavaScript
Vladislav, 2019-11-22 03:46:22

Searching for an element by the text document.querySelector, which selector to choose?

I'm trying to emulate a click by finding an element by text in it. How to write a selector correctly? Tried different designs like this one:

setTimeout(function() {
  let link = document.querySelector("//*[text()='Search FragmentX']"); 
  link.click(); 
});

element's outerHTML
<label for="x-auto-1558" htmlfor="x-auto-1558" class="x-form-cb-label" style="position: relative; left: 0.78479px; top: -0.0104141px;">Search FragmentX</label>

Full XPath
/html/body/div[4]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/form/div[1]/div[1 ]/div/table/tbody/tr[3]/td/div/label
Search by ID and other standard parameters is not an option

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav, 2019-11-22
@vlatek

Decision

setTimeout(function() {
  let link = document.querySelectorAll('label');  //собираем все элементы label в nodelist
  link = Array.from( link ).filter( e => (/Текст/i).test( e.textContent ) ); //переводим в массив и фильтруем по тексту
  link[0].click();  //кликаем по первому элементу массива
});

A
Alexey Sundukov, 2019-11-22
@alekciy

The XPath itself is incorrect. //*[text()='Search FragmentX'] will return an unnamed text node containing the given text (i.e. not even a label, but a node inside this label). And onclick on it may not be. There is also an option that at the time of calling this code and clicking in the DOM there is no handler yet. Because it is not clear how this code is called and at what point.
And if you link to the x-form-cb-label class (as an experiment), does such a click work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question