KingKongFrog
KingKongFrog

Reputation: 14419

Find DOM element in text content using javascript

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?

Upvotes: 1

Views: 842

Answers (4)

brbcoding
brbcoding

Reputation: 13596

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

Upvotes: 0

Eran Boudjnah
Eran Boudjnah

Reputation: 1278

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

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

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)

Upvotes: 4

bbuecherl
bbuecherl

Reputation: 1619

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

var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");

Upvotes: 0

Related Questions