Search code examples
javascriptbookmarklet

Bookmarklet to click a specific div element with no id


I need a bookmarklet to click one of many div elements with the class "site-label-text selectedResource". I know how to write a bookmarklet that clicks on an element by the element's ID or name, but this particular element has neither.

The specific element I want to click can be identified by its innerText or textContent properties, which are both "33".

I was going to try searching the text contents of all elements with the class "site-label-text selectedResource", but it seems that, in bookmarklets, getElementBy__ works, but getElementsBy__ (plural) doesn't. And even if that worked, I'm not sure how I can use that to specify the element I want clicked.

Another option I've read about is to use the XPATH. I found the element's XPATH

/html/body/app-root/mat-sidenav-container/mat-sidenav-content/div[2]/main/app-create-booking/app-search-results/div/div[2]/div/app-map-view/div/div[1]/div/div[2]/div/div[1]/div[4]/div[167]

but I don't know the command to "click" it.

So I'm not sure what to do. Can anyone help?


Solution

  • If you want to select multiple elements based on a class-name you can use document.querySelectorAll.

    It should look something like this:

    javascript: (() => {
      // Select all elements with target class-name.
      const elements = document.querySelectorAll('.site-label-text selectedResource');
    
      // Filter those elements based on their contents.
      const filteredElements = [...elements].filter(e => e.innerHTML === '33');
    
      // Synthesize a "click" event.
      filteredElements.forEach(e => e.click());
    })();