Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get div value from a string

I have the following string

str ='<div id="example">Text</div><div id="test">Test</div>';

how can I get the example and test content with jQuery.

like image 747
OHLÁLÁ Avatar asked Dec 27 '22 17:12

OHLÁLÁ


1 Answers

You need to convert the text to a jQuery object and then use standard traversing methods

str ='<div id="example">Text</div><div id="test">Test</div>';
var live_str = $('<div>',{html:str});

var example = live_str.find('#example').text();
// example variable now holds 'Text'

var test = live_str.find('#test').text();
// example variable now holds 'Test'

demo at http://jsfiddle.net/gaby/FJSm6/


As you see i set the string as the html of another element, because otherwise the divs would be at the top level and you would not be able to traverse them with .find()..

like image 70
Gabriele Petrioli Avatar answered Dec 30 '22 07:12

Gabriele Petrioli