简体   繁体   中英

How to get a selected div portion from a variable containing html code by using javascript?

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

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.net/xndKN/1/

The easiest way with jQuery in my opinion:

var message = $('<div />').append(html).find('#message').text();
                                                      //.html();
// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM