I'm trying to make a script and I need to grab an element on a webpage. I inspect the page and select the element with the help of chrome, I copy the css code of that element and the result is:
<a id="4edd60cf-0462-4b8b-9b60-1d41911f3309" href="javascript:void(0);">Join now.</a>
The problem is when I clear all the cache& cookies, the id of the element changes.
Are there any other methods to grab that?
I've tried to use the chrome's "copy selector" function but it doesn't work
答案 0 :(得分:1)
if you have no attribute to use, you can use the text of the element.
const link = [...document.querySelectorAll('a')].find(e => e.text === 'Join now.')
if(link)
link.style.color = 'green' // do something with the found link.
<a id="4edd60cf-0462-4b8b-9b60-1d41911f3309" href="javascript:void(0);">Join now.</a>
答案 1 :(得分:0)
If you're happy enough to fetch the element using the text content, you can do so using xPath. Here's a basic JavaScript example with a button to demonstrate...
// xPath of element you want to find
var xpath = "//a[contains(text(),'Join now')]";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
// Button code for demonstration purposes
document.getElementById("test").onclick = function () {
alert(matchingElement.id); };
<a id="not-this" href="javascript:void(0);">Don't join.</a>
<a id="4edd60cf-0462-4b8b-9b60-1d41911f3309" href="javascript:void(0);">Join now.</a>
<a id="not-this" href="javascript:void(0);">Now join.</a>
<br><br>
<button id="test">Get the ID</button>