1

Please push me towards a duplicate of this question if possible. I've looked everywhere but can't seem to find it.

How do I do a getElementById on text content?

var test = '<div id="thisDiv">HI</div>';

How do I select thisDiv if it's not a part of the DOM?

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124

4 Answers4

4

Create an element, set your string as its innerHTML and then search inside that ...

Something like

var test = '<div id="thisDiv">HI</div>';
var element = document.createElement('DIV');
element.innerHTML = test;

alert(element.textContent);

(changed the initial outerHTML as you can only maintain a reference to the originaly created element, and not the new one that is created by the new html)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

For getting the text value inside your tags, use RegEx:

var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");
bbuecherl
  • 1,609
  • 12
  • 20
0

You could create a temporary DIV and populate it with your string. Even then, your ability to access it would be limited. Add it to the DOM to access it using getElementById.

var div = document.createElement('div');
div.innerHTML = '<div id="thisDiv">HI</div>';
alert(div.firstChild);
Eran Boudjnah
  • 1,228
  • 20
  • 22
0

To avoid creating that extra element, we could just add it to the body...

var test = '<div id="thisDiv">HI</div>';
document.querySelector('body').innerHTML = test;
console.log(document.getElementById('thisDiv'));

Obligatory Fiddle

Getting just the text...

console.log(document.getElementById('thisDiv').textContent); // returns HI
brbcoding
  • 13,378
  • 2
  • 37
  • 51