简体   繁体   中英

Add CSS via javascript to an element works in console but not in html structure

I want to add css (margin-top) to an element on woocommerce checkout page that contains the card error messages.

This is the code:

const cardError = document.getElementsByClassName('sumo-pp-stripe-card-errors');
cardError[0].style.marginTop = '100px';
console.log(cardError[0]);

It works fine when I look at it in the console tab. 在此处输入图片说明

But in the real html structure I can not see any changes. 在此处输入图片说明

What have I done wrong?

To add to html

<div id="myDIV">
This is a DIV element.
</div>

First make a css class you can change your desire css style inside here

.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
  box-sizing: border-box;
}

then write js like this

 var element = document.getElementById("myDIV");
   element.classList.add("mystyle");

 const cardError = document.querySelector('.sumo-pp-stripe-card-errors'); cardError.style.marginTop = '100px';
 <div class="sumo-pp-stripe-card-errors"> some test div </div>

Well this works Check!

You need to make sure that your JavaScript runs after the DOM contains the elements.

If you are adding the JavaScript code to the page itself, insert your <script> element at the end of the <body> element.

If you are adding your code to an existing script that is at the start of the document, put your code in a function, then call that function when the DOM has loaded. Like this: document.addEventListener("load", myFunction)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM