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 . .

Share Improve this question edited Dec 22, 2011 at 11:12 Francis Mv asked Dec 22, 2011 at 11:08 Francis MvFrancis Mv 831 silver badge5 bronze badges 2
  • 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
Add a ment  | 

5 Answers 5

Reset to default 3

The 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

本文标签: