html - 将属性添加到动态创建的表
问题描述
直升机,
我正在使用生成报告的外部软件。我正在获取表格,然后将其打印到 div 中的网站。在生成此表之前我无权访问它,因此在呈现网站之前我无法设置任何属性。
所以我需要在这个表中添加属性作为渲染过程的最后一步,不管是 ID 还是 Class。
结构如下:
<div class="data" id="Checklist">
<p>Some text</p>
<!-- There is this table -->
<table style="...">...</table>
<p></p>
</div>
我正在使用 IE v11。
我尝试了这样的事情(没有任何反应):
document.getElementById("Checklist").childNodes[0].className = "TestClassName";
另外(它给出了mi错误:对象不支持属性或方法'setAttribute')
document.getElementById('news').childNodes[0].setAttribute( 'class', new_class );
还有其他想法吗?
解决方案
如果您使用 ChildNodes 它将返回所有带有 nodelist 的空白空间,因此请使用 children 以便它只返回子元素
<div class="data" id="Checklist">
<p>Some text</p>
<!-- There is this table -->
<table style="...">...</table>
<p></p>
</div>
将您的 js 更改为
document.getElementById("Checklist").children[0].className="TestClassName";
document.getElementById('news').children[0].setAttribute( 'class', new_class );
它会起作用的