Search code examples
javascriptgetclickhtml-listselement

getElementsByTagName() and text inside .click


I have clickable list elements, same class and role, and just text inside is different. I need to chose one and click same (text) li element all the time. This function document.getElementsByTagName("li")[5].click() works, but sometimes index change and pres wrong line. i have same value all the time like "222" but index may be different, how to .click not by tag name, but text?

<ul>
            <li>111</li>
            <li>222</li>
            <li>333</li>
            <li>444</li>
</ul>

thanks,


Solution

  • You have to iterate through li and check content of each one

    for (element in document.getElementsByTagName("li")) {
      if (element.textContent === '222') {
        element.click();
        break;
      }
    }
    

    https://www.w3schools.com/jsref/prop_node_textcontent.asp

    Or you can try to build querySelector. But I'm not sure if it supports content. https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector