首页 > 解决方案 > 如何在 Squarespace 模板中使用 Javascript 设置 H1 标签样式

问题描述

我们的 Squarespace 网站有一个目录,其中包含来自多个品牌的产品。我试图通过使其粗体来确保品牌名称脱颖而出,但考虑到 Squarespace 的工作方式,我需要在页面中添加 Javascript 来操作 html。

在产品标题上使用 Chrome 开发工具,我可以看到 html 类名为“.ProductList h1.ProductList-title”。

我已经尝试实现以下内容,但到目前为止还没有多少运气 - 我是否走在正确的轨道上?

function changeBrandName() 
{
  var prodList = document.getElementsByClassName(".ProductList h1.ProductList-title");
  for (i = 0, len = prodList.length; i < len; i++) 
  {
    prodList[i].style.color = 'red';
  }
}

window.onload = changeBrandName();

Squarespace 类结构:

<section class="ProductList-overlay">
          <div class="ProductList-meta">
            <h1 class="ProductList-title">Vifa - Pebble Grey Oslo Loudspeaker</h1><style></style>                                                 
            <div class="product-price">
<span class="sqs-money-native">0.00</span>
</div>
          </div>
        </section>

(这是我们展示产品的页面之一https://www.manilva.co/catalogue-electronics/)。

标签: javascripthtmlsquarespace

解决方案


看看:https ://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

当使用 getElementsByClassName 时,您不需要像您所做的那样传入 CSS 选择器。您只需要传入类的实际名称。或者,将 querySelectorAll 与您最初的参数一起使用。正如 daksh 所提到的,querySelector 只会返回匹配的第一个元素

function changeBrandName()
{
  var prodList = document.querySelectorAll(".ProductList h1.ProductList-title"); //returns static NodeList of all elements in DOM that match the provided classes
  for (i = 0; i < prodList.length; i++) 
  {
    prodList[i].style.color = 'red';
    prodList[i].style.fontWeight = 'bold'; //W is capital
  }
}

推荐阅读