复制并分配文档对象的本机方法(Copy and assign native method of document object)

编程入门 行业动态 更新时间:2024-10-24 12:23:50
复制并分配文档对象的本机方法(Copy and assign native method of document object)

我想在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 tag

See also Converting HTML string into DOM elements?

更多推荐

本文发布于:2023-04-28 02:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329813.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:本机   分配   对象   文档   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!