我想在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>
I want to perform the document.getElementById() method on the String object.
String.prototype.getElementById = document.getElementById; test = new String('<p id="para1">Irgendein Text</p>'); console.log(test.getElementById("para1"))The above attempt returns: Uncaught TypeError: Illegal invocation
Is there a way to perform the getElementByID method on a string?
Edit:
Thanks works like a charm:
var test = (new DOMParser()).parseFromString('<dummy/>', 'text/xml'); test.getElementsByTagName('dummy')[0].innerHTML = '<p id="para1">Irgendein Text</p>'; console.log(doc.getElementById('para1'));Returns <p id="para1">Irgendein Text</p>
最满意答案
字符串不是文档,因此不能通过getElementById等DOM方法遍历它。 听起来您想将字符串视为dom选择,然后对其运行查询。 querySelector允许您对一大块DOM或整个文档运行查询,以便您可以使用它。 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另请参阅将HTML字符串转换为DOM元素?
A string is not a document, so it can't be traversed by DOM methods like getElementById. It sounds like you want to treat a string as a dom selection and then run a query on it. querySelector lets you run a query on a chunk of DOM or the whole document so you can use that. document.querySelector('#id') will yield the same set of elements as document.getElementById('id').
An easy way to turn a string into DOM is to set it to the innerHTML of another element. So
var wrapper= document.createElement('div'); wrapper.innerHTML= '<p id="para1">Irgendein Text</p>'; console.log(wrapper.querySelector('#para1')); // your p tagSee also Converting HTML string into DOM elements?
更多推荐
发布评论