Setting the attribute value of a particular DOM element using Playwright

87 views Asked by At

Screenshot

I am trying to set the attribute **src** value under <img> tag to some content. I am using playwright and typescript to change it. Below is the piece of code

await this.page.addInitScript(() => {
       window.addEventListener('DOMContentLoaded',()=>{

          const imageUrl = document.getElementById("'image-" + ImageLandingSteps.IMAGE_ID + "'");
          imageUrl.setAttribute('src','fhfdadsafsdf');
        });
      });

I have attached an image to have a clear picture. basically I am trying the find the Element by id first and then on that I am setting the attribute value

Earlier I used Cypress invoke command on locator to set some attribute value and it worked .

Anything which I am doing incorrectly. Please suggest

1

There are 1 answers

0
szogoon On

To do it more Playwright way, you could do it like:

const image = page.locator(`#image-${ImageLandingSteps.IMAGE_ID} img`);
await image.evaluate(element => element.setAttribute('src','fhfdadsafsdf'));