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?

7
  • 5
    But.... how can you getElement, if it's not an element...? Commented Dec 30, 2013 at 20:54
  • 4
    You have a string there, not a DOM element. Commented Dec 30, 2013 at 20:54
  • What's the easiest way to get the value then of thisDiv if it's a string? Commented Dec 30, 2013 at 20:56
  • use RegEx (e.g. /<(.|\n)*?>/g) Commented Dec 30, 2013 at 20:57
  • Check this answer: stackoverflow.com/a/3104237/2563028 Commented Dec 30, 2013 at 21:00

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.