syntaxcode
syntaxcode

Reputation: 133

How to retrieve xml href and target attributes into DIV using jquery .load

I have an xml within my domain and I want to retrieve the xml nodes and convert a div with title link (href url and target href attributes) from the xml nodes.

Here's my xml

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <title>This is my Title</title>
    <url>http://stackoverflow.com/</url>
    <url_target>_blank</url_target>
</xml>

HTML:

<div id="title">
<a href="" target="" id="title_with_link"></a>
</div>

I'm using a jquery .load

<script>
var xmlpath = "myxml.xml";
    $( "#title_with_link" ).load(xmlpath+ " title"); 
    $( "#title_with_link a" ).load(xmlpath+ " url").attr('href'); // this is not working
    $( "#title_with_link a" ).load(xmlpath+ " url_target").attr('target'); // this is not working
</script>

My target result should be

<a href="http://stackoverflow.com/" target="_blank" id="title_with_link">This is my Title</a>

I can load the title, but not with the correct href and target attributes.

Upvotes: 0

Views: 222

Answers (1)

Diptox
Diptox

Reputation: 1809

Demo

/*
    You can use get to load your XML content to the xmlDoc var
*/

var xmlDoc = $.parseXML( '<?xml version="1.0" encoding="UTF-8"?>'+
'<xml>'+
    '<title>This is my Title</title>'+
    '<url>http://stackoverflow.com/</url>'+
    '<url_target>_blank</url_target>'+
'</xml>' );

var xml = $( xmlDoc );

$(".yo").text('<a href="'+xml.find("url").text()+'" target="'+xml.find("url_target").text()+'" id="'+xml.find("url").text()+xml.find("title").text()+'">'+xml.find("title").text()+'</a>');

Upvotes: 1

Related Questions