如果变量获取,则删除 class

Delete class if variable get

如果有变量get(SID)需要删除已有的class(forceview)

Url 例子:https://example.com/?SID=eqwe7q7e6868

我正在获取变量并尝试插入显示 (none)。

function sid() {
  // Gets a url that includes the `?` character
  var url = "somedomain.net?search";
  if (url.indexOf("?") > 0) {
    // Selects elements with the "forceview" class
    const forceviews = document.getElementsByClassName("forceview");
    // Loops through these elements and removes them from display
    for (let forceview of forceviews){
      forceview.style.display = "none";
    }
    console.log("all `.forceview` elements have been hidden");
  }
}
sid();
span.old-price.sly-old-price.no-display.forceview {
    display: inline !important;
}
<span class="old-price sly-old-price no-display forceview">
  <span class="price-container price-final_price tax weee">
    <span class="price-label">Preço Normal
    </span>
    <span id="old-price-1263-final_price" data-price-amount="19.9" data-price-type="oldPrice" class="price-wrapper ">
      <span class="price">R,90</span>
    </span>
  </span>
</span>

代码returns没有错误。

document.getElementsByClassName() 不接受 css 选择器。 你应该写

document.getElementsByClassName("forceview")[0]

[0] beacuse document.getElementsByClassName returns an array of elements.

这是你想做的吗?

function sid() {
  // Gets a url that includes the `?` character
  var url = "somedomain.net?search";
  if (url.indexOf("?") > 0) {
    // Selects elements with the "forceview" class
    const forceviews = document.getElementsByClassName("forceview");
    // Loops through these elements and removes them from display
    for (let forceview of forceviews){
      forceview.style.display = "none";
    }
    console.log("all `.forceview` elements have been hidden");
  }
}

sid();
<span class="old-price sly-old-price no-display forceview">
  <span class="price-container price-final_price tax weee">
    <span class="price-label">Preço Normal
    </span>
    <span id="old-price-1263-final_price" data-price-amount="19.9" data-price-type="oldPrice" class="price-wrapper ">
      <span class="price">R,90</span>
    </span>
  </span>
</span>

我看到很多错误:

• 你应该 运行 你的函数在函数之外(而不是在函数内部)。

• 您尝试用 getElementById 获得 class,我认为您应该使用 getElementsByClassName

• 您正在循环 spans.length 但什么是跨度?你不在任何地方声明它。