views:

41

answers:

3

I have an xml file like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<legends>
<legend>
<number>1</number>
<legendString><ul><li>1.across:a system of rules of conduct or method of practice</li><li>1.down:a disagreement or argument about something important</li><li>2.down:any broad thin surface</li><li>3.across:the passage of  pedestrians or vehicles </li></ul></legendString>
</legend>
......
<legends>

How can I take whole text including tags using jQuery. The string

<ul><li>1.across:a system of rules of conduct or method of practice</li><li>1.down:a disagreement or argument about something important</li><li>2.down:any broad thin surface</li><li>3.across:the passage of  pedestrians or vehicles </li></ul>

should be passed if I make a function call. If I call:

var legendStr = $(this).find("legendString").text();

tags will not be present in legendStr.

How can I proceed.

This is the jQuery Script:

var randomnumber=Math.floor(Math.random()*233);
    $.get("legends.xml",{},function(xml){  



       $(xml).find("legend").each(function(){   


                if(randomnumber == $(this).find("number").text())
                {
              var c = "legendString";

              var legendStr = $(this).find(c).html();         


              $("#sidebar > ul").html(legendStr);
                }



       });
       },"xml");
A: 

Try using the .html() method to preserve tags:

var legendStr = $(this).find('legendString').html();

Also note that .find('legendString') will look for a tag called legendString which probably is not what you are looking for. You probably need the :contains() selector.

Darin Dimitrov
This is not working out.
Vinod
*Not working* is not a very precise problem description. Could you post a complete snippet that illustrates the issue?
Darin Dimitrov
@Darin, Can you please look at the updated code.
Vinod
A: 
William
A: 

I don't think the function you need is in jQuery out-of-the-box. But you can write your own. Here is a starting point for you:

jQuery.extend(jQuery.fn, {
outerHtml: function(tagName) {
    var matches = this.find(tagName);
    var result = '';
    for (var i=0; i<matches.length; i++) {
        var el = matches[i];
        result += '<' + tagName;

        for (var i=0; i<el.attributes.length; i++) {
            result += ' ';
            result += el.attributes[i].name;
            result += "='";
            result += el.attributes[i].value;
            result += "'";
        }
        if (el.innerHTML == null) { result += '/>'; }
        else { 
        result += '>';
        result += el.innerHTML;
        result += '</'
        result += tagName;
        result += '>';
    }
    return result;
}

}});

thus, you'll be able to do

var legendString = $(this).outerHtml('legendString');