admin管理员组文章数量:1360385
I have a variable var 'html'
, it contains some html codes .in it there is a div with id messages
. I want to get only that div contents from the 'html' variable into another variable using javascript.
Please help . .
I have a variable var 'html'
, it contains some html codes .in it there is a div with id messages
. I want to get only that div contents from the 'html' variable into another variable using javascript.
Please help . .
- 2 See stackoverflow./questions/704679/… – jaybee Commented Dec 22, 2011 at 11:11
- can you post the content of html variable? – Amit Rai Sharma Commented Dec 22, 2011 at 11:26
5 Answers
Reset to default 3The easiest way with jQuery in my opinion:
var message = $('<div />').append(html).find('#message').text();
//.html();
If it's valid HTML, you don't even have to append it to the DOM:
var html = "<div id='wrapper'><div id='messages'>Messages!</div></div>";
// Create DOM node (subtree) from the string (but don't append to the document):
var node = $(html);
// Find the messages div:
var messages = node.children('#messages');
// Get the contents of the div:
var result = messages.text();
Edit: here's a working example: http://jsfiddle/xndKN/1/
// your html code
var html = '...';
// add a temporary div
$('<div id="temp" style="display:none">'+html+'</div>').appendTo('body');
// extract the data inside the 'message' div
var message = $('#temp #message').text();
// remove temporary div
$('#temp').remove();
Now, the variable message
will contain the text inside the div with id 'message'
First of all you question is not giving enough information about your situation. You have not posted the code. Anyway if you try the following you will get access the the message div.
var o = $("<html><body><div id='parent'><div id='message'>Hello</div></div></body></html>")
$(o).children("#message").text()
I have tried it on Chrome Developer tool and it is working.
try
var myhtml = "here is my data outside div
<div id='message'>inside div with id message</div>";
var node = $(myhtml);
$(node).append(myhtml);
alert($(node).find('div#message').text());
WORKING DEMO
本文标签:
版权声明:本文标题:jquery - How to get a selected div portion from a variable containing html code by using javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743898928a2558310.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论