Text
Test
'; how can i get an example an...">

Get div value from string

I have the following line

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

how can i get an example and check the contents using jQuery.

+4
source share
3 answers

You need to convert the text to a jQuery object and then use the standard move 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 can see, I am setting the line as the html of another element, because otherwise the divs will be at the top level and you cannot cross them with .find() ..

+7
source

You can always create a min-DOM (if you want) by passing valid HTML code to jQuery:

 $(str).wrap('<p>').parent().find('div').text(); 

So:

 var textContent = $(str).wrap('<p>').parent().find('#example').text(); var testContent = $(str).wrap('<p>').parent().find('#test').text(); 
+3
source

The easiest way is to save the contents in var and work with it:

 var example = $('#example').text(), test = $('#test').val(); 

You can also get content using .html () if you want to also capture html tags if necessary.

0
source

All Articles