3

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>

Niko
  • 57
  • 1
  • 6
  • I can understand (a little bit) wanting to be able to say `someId.getElementById()`, although it seems to be just a minor improvement over `document.getElementById(someId)`, but your example stumps me--you somehow want to find an element by passing in a string of HTML from which the ID is somehow to be extracted? Are you sure you don't just want to do `document.querySelector('p#para1')`? –  Jul 27 '16 at 22:32
  • Yes, i realized that my code has no applications, i will use document.querySelector() instead. – Niko Jul 27 '16 at 23:51

1 Answers1

2

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?

Community
  • 1
  • 1
chiliNUT
  • 18,989
  • 14
  • 66
  • 106