0

I am just starting to learn some basics of javascript related to html. I would like to know is there a way to select the html element by its visible text?

For example: If I would like to click the “Interesting” button on the stackfoverflow page I can find the element by querySelector.

stack overflow html page code sample:

<a class="youarehere is-selected flex--item s-btn s-btn__muted s-btn__outlined" 
    href="?tab=interesting" 
    data-nav-xhref="" 
    title="Questions that may be of interest to you based on your history and tag preference" 
    data-value="interesting" data-shortcut="">
        Interesting
</a>

one way of locate the html element:

document.querySelector("a[class='youarehere is-selected flex--item s-btn s-btn__muted s-btn__outlined']").click()

I know there might be some other ways to locate the element, but am I able to locate the element by the visable text “Interesting”? Thanks if anyone knows how.

stack overflow page html sample image down below.

stack overflow html sample

wazz
  • 4,953
  • 5
  • 20
  • 34
  • 2
    Yes but it would require querying every element for it's innerText. This is not native and will comparatively slow. This may also match elements that wrap the desired element too. – phuzi Jan 08 '22 at 14:23
  • 1
    If it's just the text content you want to match, then you are stuck checking every element, as @phuzi mentioned. The only way to cut this down is by reducing the search area to only child elements of a container, or to scan only elements of a certain type (e.g. anchor tags, elements with a given class name, etc.). – GenericUser Jan 08 '22 at 14:35
  • Check this Answer: https://stackoverflow.com/a/17799291/11286971 I think this will inspire you – Zaid abu khalaf Jan 08 '22 at 14:39
  • Also, it's a bad practice query elements `class` attribute, because if anything in the class changed (i.e. order of classes), your query will fail. You should query it like `a.youarehere.is-selected.flex--item` instead. Another trick is to find something unique in it's parent elements, and query by that, i.e in this particular case: `#mainbar div.s-btn-group>a[data-value="intersting"]` – vanowm Jan 08 '22 at 16:08
  • Thanks for the information provided. Appreciated. – user8142184 Feb 22 '22 at 01:25

0 Answers0