首页 > 解决方案 > 替换js中的元素时HTMLCollection显示?

问题描述

我正在尝试将 Html(Div) 替换为文本元素首先我创建了您可以在此处看到的条件

html

<!-- Replace Text Here-->
<h6 class="idk1"> Replace This  </h6>
<!-- Main Column -->

<div class="js-cp-main-wrp">
<div class="support-2">
<html>stuff here</html>
</div>
<div class="end-cp-wrp">
<html>stuff here</html>
<html>stuff here</html>
<html>stuff here</html>

</div>
</div>

脚本

    var woahtikcets = document.getElementsByClassName('js-cp-main-wrp');
    const loadthetickets = document.getElementsByClassName('idk1');

运行这个

loadthetickets.replaceWith(woahtikcets)

它告诉我 [object HTMLCollection] ??

这种方法不起作用它叹为未定义?请帮助<3

 const loadthetickets = document.getElementsByClassName('idk1')[0];

标签: javascripthtml

解决方案


我完全不确定您的意图是什么,但<html>不仅仅是HTML 中的一些标签 。它必须是外部标签(文档的根),因此只能在文档中出现一次。因此,如果您将<html>元素替换为其他(合法)实体,<span>您很可能会得到一些结果,如下所示:

 const woahtikcets = document.querySelectorAll('.js-cp-main-wrp span'),
       newtext = document.getElementsByClassName('idk1')[0].textContent;

for (var el of woahtikcets){el.textContent=newtext}
<!-- Replace Text Here-->
<h6 class="idk1"> Replace This  </h6>
<!-- Main Column -->

<div class="js-cp-main-wrp">
<div class="support-2">
<span>stuff here</span>
</div>
<div class="end-cp-wrp">
<span>stuff here</span>
<span>stuff here</span>
<span>stuff here</span>

</div>
</div>

如果您希望替换操作以相反的方向工作,您可以执行以下操作:

const newtext = document.querySelectorAll('.js-cp-main-wrp')[0].textContent,
      heading = document.getElementsByClassName('idk1');

for (var el of heading){el.textContent=newtext}
<!-- Replace Text Here-->
<h6 class="idk1"> Replace This  </h6>
<!-- Main Column -->

<div class="js-cp-main-wrp">
<div class="support-2">
<span>stuff here</span>
</div>
<div class="end-cp-wrp">
<span>stuff here</span>
<span>stuff here</span>
<span>stuff here</span>

</div>
</div>


推荐阅读