【问题标题】:How to remove an element with HTML DOM?如何使用 HTML DOM 删除元素?
【发布时间】:2017-08-01 07:12:21
【问题描述】:

我使用 CasperJS 从网站 http://www.u-movie.com.tw/page.php?page_type=now&portal=cinema&ver=tw 获取数据。

我想删除没有id的<p>

所以我尝试选择根并删除它,但它会显示null is not an object

如果我不使用 jQuery,只使用 javascript,我该如何解决?

任何帮助将不胜感激。

这是我的文件的一部分:

这是我的代码:

function getMovieTime() {
    this.evaluate(function () {
        var time = document.querySelectorAll('ul.posts p');
        time.parentNode.remove();
        time = document.querySelectorAll('ul.posts');
        return Array.prototype.map.call(time, function (e) {
            return e.innerText;
        });
    });
};

我调用 getMovieTime():此代码报告 null

var movieTime = [];  // global variable
casper.then(function () {
    movieTime = this.evaluate(getMovieTime);
});

【问题讨论】:

  • 报告了null is not an object 的哪一行?
  • 我更新了我的问题,我调用 getMovieTime 函数导致报告为空。
  • 报告哪一行?对于this.evaluate(function () { ?打电话给this.evaluate(getMovieTime) 然后在getMovieTime 内部再次调用this.evaluate(function () { 是没有意义的。
  • 是的……还有一点,谢谢提醒。

标签: javascript phantomjs casperjs simple-html-dom


【解决方案1】:

首先,

方法 node.remove() 在 DOM 4 规范中实现。 但是由于浏览器支持不佳,您不应该使用 它。

然后,您可以尝试替换它。

这里

var parent = document.getElementById("latest_posts");
var child = document.getElementById("posts");
var para = document.createElement("p");
var node = document.createTextNode(" ");
para.appendChild(node);
parent.replaceChild(para,child);

注意 - 你应该使用getElementsByClassName 而不是getElementById

【讨论】:

  • 感谢您的回复,但我无法理解。我的文档中没有 id 。我怎样才能从你的代码中完成它? getElementById
  • 根据问题中显示的标签和代码,remove 是使用 phantomjs 的上下文,因此只要当前版本的 phantomjs 支持,浏览器支持并不重要。
  • OP 在哪里使用getElementsByClassNamegetElementById。代码仅显示querySelectorAll.getElementById("latest_posts") 是错误的,因为该元素具有latest_posts
  • @t.niese。我提到他应该在注释下理想地使用 getElementsByClassName。这只是替换的一个例子。此外,不知道 casper 或 phantom。因此没有更正原代码
  • 我的想法是让你使用`replace`而不是remove。您可以继续使用 querySelectorAll
猜你喜欢
  • 1970-01-01
  • 2015-05-20
  • 2012-01-03
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 2011-10-24
相关资源
最近更新 更多