【问题标题】:Why am I able to remove certain elements using document.getElementsByClassName() but not others?为什么我可以使用 document.getElementsByClassName() 删除某些元素,但不能删除其他元素?
【发布时间】:2021-01-26 20:55:27
【问题描述】:

我正在尝试在 ViolentMonkey 中创建一个简单的脚本以在 Letterboxd.com 电影页面上运行 - 例如https://letterboxd.com/film/mirror/.

我的目标是从页面中删除某些元素 - 即平均评分和 Facebook 分享按钮。

我的脚本如下所示:

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
var rating = document.getElementsByClassName('average-rating')
 $(rating).remove()
 console.log("Rating removed!")
var sidebar = document.getElementsByClassName('panel-share')
 $(sidebar).remove()
 console.log("Panel removed!")
});

类“panel-share”(facebook 分享按钮)的元素被删除,没问题。但是,“平均评分”类的元素仍然存在。

我尝试像这样删除节级父元素(它有两个类,“section”和“ratings-histogram-chart):

var chart = document.querySelector('.section.ratings-histogram-chart')
$(chart).remove()
console.log("Chart removed!")

但还是没有运气……其实querySelector根本不起作用。

谁能帮我解决这个问题?我觉得我在做一些非常明显的错误,但我很新。非常感谢。

编辑:我试图运行它的 HTML 是:

var rating = document.getElementsByClassName('average-rating')
$(rating).remove()
console.log("Rating removed!")
var sidebar = document.getElementsByClassName('panel-share')
$(sidebar).remove()
console.log("Panel removed!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="average-rating" itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating"> <a href="/film/mirror/ratings/" class="tooltip display-rating -highlight" data-original-title="Weighted average of 4.29 based on 35,429&nbsp;ratings">4.3</a> </span>

<li class="panel-share">
  <div id="share-off" style="display: block;"><a href="#">Share</a></div>
  <div id="share-on" style="display: none;"> <input type="text" class="field -transparent" value="https://boxd.it/28Q8" readonly="" spellcheck="false"> <a href="https://twitter.com/intent/tweet?text=Mirror%20%281975%29%20on%20%40letterboxd%3A%20https%3A%2F%2Fboxd.it%2F28Q8" class="replace popup-link tw-popup"
      title="Tweet a link">Tweet</a> <a href="https://www.facebook.com/dialog/feed?app_id=173683136069040&amp;link=https%3A%2F%2Fletterboxd.com%2Ffilm%2Fmirror%2F&amp;picture=https%3A%2F%2Fa.ltrbxd.com%2Fresized%2Ffilm-poster%2F5%2F1%2F0%2F6%2F4%2F51064-mirror-0-230-0-345-crop.jpg%3Fk%3D8287891685&amp;name=Mirror%20%281975%29%20on%20Letterboxd.com&amp;caption=Directed%20by%20Andrei%20Tarkovsky&amp;description=A%20dying%20man%20in%20his%20forties%20recalls%20his%20childhood%2C%20his%20mother%2C%20the%20war%20and%20personal%20moments%20that%20tell%20of%20and%20juxtapose%20pivotal%20moments%20in%20Soviet%20history%20with%20daily%20life.&amp;message=&amp;display=popup&amp;redirect_uri=https://letterboxd.com/facebook-share"
      class="replace popup-link fb-popup fbc-has-badge fbc-UID_1" title="Share to Facebook">Share</a> </div>
</li>

【问题讨论】:

  • 如果你使用 jQuery,为什么还要使用 DOM 函数?写$(".panel-share").remove()
  • 你为什么要同时使用jQuery和querySelector
  • 如果您需要更多帮助,请提供运行所提供 JavaScript 的 HTML 示例。您可以使用 Stack Snippets(图标在编辑器工具栏中看起来像 &lt;&gt;)来提供一个可运行的示例。
  • 您好,我已按要求添加了 html,感谢您的提示。 @HereticMonkey
  • @Barmar 不幸的是,它不适用于$(".average-rating").remove() 抱歉,如果我以一种不直观的方式做事,我主要是通过阅读这里以前的答案来学习 - 我对理论不好。我不会正常编码,只是想为此编写一个简单的脚本。

标签: javascript jquery getelementsbyclassname queryselector


【解决方案1】:

这里的问题似乎是评分图(包括平均评分)是异步加载的,因此在您的脚本运行时不存在。

为了解决这个问题,您可以侦听父 .sidebar 元素的更改,然后在它出现时立即将其删除:

$(function() {
  $('.panel-share').remove();
  
  // listen for changes of the .sidebar element
  $('.sidebar').on('DOMSubtreeModified', function() {
    if($('.average-rating').length) {
      $('.average-rating').remove();
      $(this).off('DOMSubtreeModified');
    }    
  })    
});
``

【讨论】:

    【解决方案2】:

    我添加了两组监听器,第一组(你自己的)当DOMContentLoaded时,第二组是等待document.readyState等于"complete"的快速间隔

    window.addEventListener('DOMContentLoaded',()=>{
    
      window.n=1 //as extra proof that it works, you can go later and check n on the inspect element's console
      var i=setInterval(() => {
        if(document.readyState!="complete"){window.n++;return;} //once document.readyState=="complete", the rest of the code loads(what you want to execute)
        clearInterval(i)
        console.log('DOM fully loaded and parsed');
        var rating = document.getElementsByClassName('average-rating')
        $(rating).remove()
        console.log("Rating removed!")
        var sidebar = document.getElementsByClassName('panel-share')
        $(sidebar).remove()
        console.log("Panel removed!")
      },1);
    
    })
    

    作为我的答案有效的证据,打开一个新选项卡/窗口,导航到 url https://letterboxd.com/film/mirror/ 以避免出现 cors 错误,打开检查元素并粘贴下面的代码

    var myWindow=window.open("https://letterboxd.com/film/mirror/")
    myWindow.eval(`
    window.addEventListener('DOMContentLoaded',()=>{
    
      window.n=1 //as extra proof that it works, you can go later and check n on the inspect element's console
      var i=setInterval(() => {
        if(document.readyState!="complete"){window.n++;return;} //once document.readyState=="complete", the rest of the code loads(what you want to execute)
        clearInterval(i)
        console.log('DOM fully loaded and parsed');
        var rating = document.getElementsByClassName('average-rating')
        $(rating).remove()
        console.log("Rating removed!")
        var sidebar = document.getElementsByClassName('panel-share')
        $(sidebar).remove()
        console.log("Panel removed!")
      },1);
    
    })
    `)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多