Please help me tweak my code! Need help dynamically adding <a> tags

I am creating breadcrumbs using XML with the following code:


// <![CDATA[

var root = null;

$(document).ready( function(){
	
	//insert div into hero module to accept breadcrumb
	
    $.get( "/_assets/xml/sitemap.xml", 
        function( data ) {
            root = data;
			var pathname = window.location.pathname;
			
			var local_url = "*[url=" + pathname + "]";
			var currpage = $(root).find(local_url).attr("name");
			var parentEls = $(root).find(local_url).parents();

            var mapped = $(parentEls).map(function () { 
                  var element = $(this).attr("name");
				  var element_url = $(this).attr("url");
				  var element_wrap = $(this).wrap('<a href="' + element_url + '"/>').attr("name"); //.attr("href",element_url);
				  return element_wrap; 
                    })
            	.get()
				.reverse()
				.join(" / ");
			
			$("#breadcrumb").append("<p>" + mapped + " / " + currpage + "</p>");

        } );
} );

// ]]>

The breadcrumbs are displaying perfectly, I’m just having a hard time inserting the <a> tag via .wrap() here:
Copy code

var element_wrap = $(this).wrap('<a href="' + element_url + '"/>').attr("name"); 

I want to attach a link to each element’s URL and return the name of the tag. The <a> tags aren’t being applied here, what am I doing wrong?

Thanks for any suggestions!

Hiya,

In your map calback, it would probably be better (and easier) to generate an array of strings containing HTML rather than trying to perform DOM manipulation, and them simply using that in your .append()

In the example here, I’m using .each() instead of map(), because map() is used to translate values from 1 array to another, whereas each() is used to iterate over arrays/objects.

var htmlStrArray = [];
var mapped = $(parentEls).each(function () { 
	var $this = $(this)
	htmlStrArray.push('<a href="' + $this.attr("url") + '">' + $this.attr("name") +'</a>');
});

$("#breadcrumbs").append("<p>" + htmlStrArray.reverse().join(" / ") + " / " + currpage + "</p>");

Thanks a million, that worked like a charm! One more question, do you know how I can make it so that the last parent item gets truncated? For instace, the sitemap looks like this:

<sitemap>
<home>
<products>
<credit>
<standard>
</standard>
</credit>

</products>
</home>
</sitemap

I only want the parents to go up to the home tag and stop.

Thanks for any suggestions, your response was such a great help!

jQuery added a .parentsUntil() function in 1.4 - that ought to do the trick.

You saved my hide! Thanks for taking the time to respond to my newbie question. :slight_smile: