我想对 String 对象执行 document.getElementById() 方法。
String.prototype.getElementById = document.getElementById;
test = new String('<p id="para1">Irgendein Text</p>');
console.log(test.getElementById("para1"))
以上尝试返回:Uncaught TypeError: Illegal invocation
有没有办法对字符串执行 getElementByID 方法?
编辑:
谢谢很有魅力:
var test = (new DOMParser()).parseFromString('<dummy/>', 'text/xml');
test.getElementsByTagName('dummy')[0].innerHTML = '<p id="para1">Irgendein Text</p>';
console.log(doc.getElementById('para1'));
返回 <p id="para1">Irgendein Text</p>
最佳答案
字符串不是文档,因此不能通过 getElementById
等 DOM 方法对其进行遍历。听起来您想将字符串视为 dom 选择,然后对其运行查询。 querySelector
允许您对 DOM block 或整个文档运行查询,以便您可以使用它。 document.querySelector('#id')
将生成与 document.getElementById('id')
相同的元素集。
将字符串转换为 DOM 的一种简单方法是将其设置为另一个元素的 innerHTML
。所以
var wrapper= document.createElement('div');
wrapper.innerHTML= '<p id="para1">Irgendein Text</p>';
console.log(wrapper.querySelector('#para1')); // your p tag
关于javascript - 复制和分配文档对象的本地方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38622994/