Niko Niko - 2 months ago 6x
HTML Question

Copy and assign native method of document object

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>');

The above attempt returns:
Uncaught TypeError: Illegal invocation

Is there a way to perform the getElementByID method on a string?


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?