1

I am getting html content as below:

var test='<div id="test">Raj</div>';

How can i retrieve value Raj from above html content using javascript.

6
  • say what? what do u want to do? Commented Mar 22, 2011 at 21:44
  • It seems like you already have Raj inside of a variable? I think more information might be needed here. Commented Mar 22, 2011 at 21:45
  • No, Raj just need to learn to use the {} button Commented Mar 22, 2011 at 21:46
  • @Raj, I think you have some quote problems too. Do you mean var test='<div id="test">Raj</div>'; ??? Commented Mar 22, 2011 at 21:47
  • 6
    Sigh. Again someone is voting this down and voting to close just because it is not up to Strunk and White - be nice to non-native English speaking people, people! Commented Mar 22, 2011 at 21:58

3 Answers 3

6

It sounds like you're trying to extract the text "Raj" from that HTML snippet?

To get the browser's HTML parser to do your dirty work for you:

// create an empty div
var div = document.createElement("div");

// fill it with your HTML
div.innerHTML = test;

// find the element whose text you want
test = div.getElementById("test");

// extract the text (innerText for IE, textContent for everyone else)
test = test.innerText || test.textContent;

Or in jQuery:

test = $(test).text();
Sign up to request clarification or add additional context in comments.

5 Comments

that jQuery can be vastly refined. $(test).find("#test").text(); for starters, no?
@mplungjan — You're right; I was sticking to too literal a translation of the non-jQuery version. :-)
And with a selector rather than find?
okeee, that was very minimalistic ;) A bit like x.innerText where x is a whole lotta html with only one textnode ;)
@mplungjan — Yeah, I was originally thinking about situations like <div id="foo">Foo</div><div id="bar">Bar</div> and needing to get each bit of text separately, but that's rather more complicated than what the OP is asking for, even if I'm right about what he's trying to do. ;-)
0

If you use jQuery (I cannot believe I just said that ;)) you can get at the content immediately you wrap it in $(test).html

Someone else will tell you how to get at the innerHTML using a selector since everybody here are jQuery gurus but me

Update: somebody just did while I was editing: javascript: extracting text from html - see comments or updates to that

2 Comments

How to escape all html content using javascript
@Raj What do you mean by "escape" ?
-2
var test = getElementById('test')

try that

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.