How to change the value of a style attribute with class name ‘image’ in console?

How can i change the attribute value of a class in console on a browser.

Here i want to change the margin-top from 40px to 400px, is it even possible to change from console ?

<div>
<img class="image" style="margin-top:40px;" src="#">
</div>

P.S – New to JS.

Thanks in advance.

Answer

Select the element in the element inspector. When you have done so, the element currently selected is available in the console as $0 variable.

So if you have selected the image in the element inspector, you can do

$0.style.marginTop = '400px'

in the console.

If you want to replace the whole attribute value with your own string:

$0.setAttribute('style', 'margin-top: 400px');

If you have more than one of these elements on the page, and you want to change them in a loop:

for (const image of document.querySelectorAll('img.image')) {
  image.style.marginTop = '400px';
  // or
  // image.setAttribute('style', 'margin-top: 400px');
}

Leave a Reply

Your email address will not be published. Required fields are marked *