【问题标题】:I selected an element by title with JavaScript, how can I update the css? [duplicate]我使用 JavaScript 按标题选择了一个元素,如何更新 css? [复制]
【发布时间】:2021-11-01 16:22:49
【问题描述】:

我按标题选择了一个元素。从现在开始,我想更新此文本的 css。例如。 '红色;'我该如何继续?

var node = document.querySelector('[title="40% Discount!"]');

【问题讨论】:

  • 你可以使用`style`property`node.style.color=red`

标签: javascript html css


【解决方案1】:

var node = document.querySelector('[title="40% Discount!"]').style.color = "red";
<div title="40% Discount!">40% off</div>

【讨论】:

  • 已编辑。当心,我认为我原来的帖子混淆了 jquery 和 js。
  • 非常感谢 wazz,效果很好!
  • 但是,您不应该在现代 Web 开发中使用 .style。现代解决方案是改用classList.add('class-name'),这样你就不会搞砸你的具体重量。
【解决方案2】:

您可以设置现有元素的样式属性:

const node = document.querySelector('[title="40% Discount!"]')

node.style.color = "red";

More from here

【讨论】:

    【解决方案3】:

    在现代 Web 开发中,您不应该在 JS 中使用 .style,因为它会将其添加为内联样式,因此具有最高的特异性权重,只会被 !important 覆盖。现代解决方案应该是添加一个类。

    使用classList.add('class-name') 向包含color: red; 的元素添加一个类!

    var node = document.querySelector('[title="40% Discount!"]').classList.add('red');
    .red {
      color: red;
    }
    <div title="40% Discount!">40% off</div>

    【讨论】:

    • 这个对我很有用。向锁定的 html 添加类可以节省我的时间,非常感谢 Tacoshy!
    • 如果这为您解决了问题,那么请考虑投票并将其标记为答案。
    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多