为什么我可以使用 document.getElementsByClassName() 删除某些元素而不是其他元素?

时间:2021-01-26 20:55:27

标签: javascript jquery getelementsbyclassname queryselector

我正在尝试在 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 共享按钮)的元素,没问题。但是,类为“average-rating”的元素仍然存在。

我试着像这样删除部分级别的父元素(它有两个类,“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>

2 个答案:

答案 0 :(得分:0)

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

为了解决这个问题,您可以监听父 .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');
    }    
  })    
});
``

答案 1 :(得分:0)

我添加了 2 组侦听器,第一个(您自己的)用于 when DOMContentLoaded,第二个是等待 document.readyState 等于 "complete"< /p>

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);

})
`)