简体   繁体   English

通过 javascript 将 CSS 添加到元素在控制台中工作但不在 html 结构中工作

[英]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.我想将 css (margin-top) 添加到包含卡片错误消息的 woocommerce 结帐页面上的元素。

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.但在真正的 html 结构中我看不到任何变化。 在此处输入图片说明

What have I done wrong?我做错了什么?

To add to html添加到 html

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

First make a css class you can change your desire css style inside here首先创建一个 css 类,您可以在此处更改您想要的 css 样式

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

then write js like this然后像这样写js

 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.您需要确保您的 JavaScript 在 DOM 包含元素之后运行。

If you are adding the JavaScript code to the page itself, insert your <script> element at the end of the <body> element.如果要将 JavaScript 代码添加到页面本身,请在<body>元素的末尾插入<script> <body>元素。

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.如果要将代码添加到文档开头的现有脚本中,请将代码放入函数中,然后在加载 DOM 时调用该函数。 Like this: document.addEventListener("load", myFunction)像这样: document.addEventListener("load", myFunction)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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