开发者

javascript: extracting text from html

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.


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


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


var test = getElementById('test')

try that

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜