How To Extract Content Of Html Tags From A String Using Javascript Or Jquery?
Solution 1:
Using .text() as both a 'getter' and a 'setter' we can just repeat the pattern of:
- target the element on the page we wish to fill
- give it content from the string
<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
$(function(){
var $str1 = $(str1);//this turns your string into real html
//target something, fill it with something from the string
$('#title1').text( $str1.find('h2').eq(0).text() );
$('#new1').text( $str1.find('p').eq(1).text() );
$('#title2').text( $str1.find('h2').eq(1).text() );
$('#new2').text( $str1.find('p').eq(1).text() );
})
</script>
Solution 2:
IMHO , You can do this in jquery in two steps :
Step 1) Parse the string into an XML/HTML document.
There are at least two ways to do this:
a) As mentioned by Sinetheta
var htmlString = "<html><div></div></html>";
var $htmlDoc = $( htmlString );
b) Using parseXML
var htmlString = "<html><div></div></html>";
var htmlDoc = $.parseXML( htmlString );
var $htmlDoc = $( htmlDoc );
Please refer http://api.jquery.com/jQuery.parseXML/
Step 2) Select text from the XML/HTML document.
var text = $htmlDoc.text( jquery_selector );
Please refer http://api.jquery.com/text/
Solution 3:
Well,
First of all you should clarify how you are getting the source html from your own html. If you are using Ajax you should tick the source as html, even xml.
Solution 4:
document.getElementById('{ID of element}').innerHTML
if use jquery $('selector').html();
<divid="test">hilo</div><script>alert($('#test').html());
<script>
Solution 5:
Let me preface my answer with the knowledge that I don't think I fully understand what you want to do...however I think you want to replace some (although you make it sound like all) html with some data source.
I've rigged a simple example is jsfiddle here:
This does a simple replace using jquery on a target div.
Hope this helps, good luck.
Post a Comment for "How To Extract Content Of Html Tags From A String Using Javascript Or Jquery?"