Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - Finding a selector that changes after each page render

Note: Its not my own site!

I have a button that I want to click on my project. The selector is:

#pop_1609947672477 > div > div > div.inner-content > div > div > div > button

The problem is, that the number after the #pop is changing on each refresh.

Maybe you can help me to solve this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the element you are interested in is the only element having an id that starts with #pop_ within the page, you can select it as follows:

[id^=pop_] > div > div > div.inner-content > div > div > div > button

If there are multiple elements having an id that starts with #pop_, then you will need to find out a pattern that can differentiate them.

For example, if the element you want to find always appears as the first element, you can add some additional constraints to the selector, or filter the result after the selection.

const elements = document.querySelectorAll('[id^=pop_] > div > div > div.inner-content > div > div > div > button');

// highlight the selected elements
elements.forEach(el => el.style.background = 'tomato');
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="pop_1234">
      <div>
        <div>
          <div class="inner-content">
            <div>
              <div>
                <div>
                  <button>The Element</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div id="not_pop_1234">
      <div>
        <div>
          <div class="inner-content">
            <div>
              <div>
                <div>
                  <button>Not The Element</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...