Home > Blockchain >  Trouble finding in the page source the related name/id to replace text using getElement(s)By.innerHT
Trouble finding in the page source the related name/id to replace text using getElement(s)By.innerHT

Time:11-21

I'm trying to replace some text on a webpage using a tampermonkey script but I'm having trouble identifying the proper element. I have gotten this to work in the past but it's fairly hit-or-miss.

For the source below I was thinking I should use document.getElementsByClassName("product-return-message__label product-return-message__label--pdp product-return-message__label--pdp-large").innerHTML = "blah blah blah" based on the closest class name but it's not working.

In general I am having difficulty identifying which name/id belongs to the text I want to replace when looking at the source of a webpage. If you could please identify the getElement(s) and name/id I should use based on the source below I would be grateful! Thanks!

partial source: ... <div data-test="message"><svg aria-hidden="true" role="img" viewBox="0 0 100 100" ></svg><div data-test="message-content"><div aria-level="2" data-test="message-label" role="heading">TEXT I WANT TO REPLACE</div> ...

CodePudding user response:

how about using document.querySelector with attribute CSS selector ?

const element = document.querySelector("div[data-test='message-label']");

if(element) {
  element.innerHTML = "found!";
}
<div class="product-return-message product-return-message--pdp product-return-message--pdp-large" data-test="message">
<div class="product-return-message__content product-return-message__content--pdp product-return-message__content--pdp-large" data-test="message-content"><div aria-level="2" class="product-return-message__label product-return-message__label--pdp product-return-message__label--pdp-large" data-test="message-label" role="heading">TEXT I WANT TO REPLACE</div>
<svg aria-hidden="true" role="img" viewBox="0 0 100 100" class="product-return-message__icon"></svg>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

QuerySelector would be help. Like @Tareq you can search by div[data-test='message-label'] or in you case: document.querySelector('div > div > div').innerHTML = Hello World. The more pleasant way of these two variants is the one by tareq.

  • Related