Reputation: 115
My html looks like this:
<div id="ProductCode"><span>Product number</span>2100022</div>
With jQuery, I want to change code to this:
<div id="ProductCode"><span>Product number</span><a href=”http://www.site.com/2100022”>2100022</a></div>
Any ideas how to do this? Thanks!
Upvotes: 0
Views: 2423
Reputation: 406
Try the following:
it will get you the product ID and wrap it on anchor tag]
var $root = $('#ProductCode');
var $span = $root.children('span');
$span.remove();
$root.wrapInner('<a href="http://www.site.com/'+$root.text()+'"></a>');
$root.prepend($span);
Upvotes: 0
Reputation: 182
you can use 'replaceWith' method for converting your text into a href on page load or where ever you want but befor do this put your text into a span than use this code. example
$('.link').replaceWith(function() {
var url = $.trim($(this).text());
return '<a href="http://www.site.com/2100022" target="_blank">' + url + '</a>';
});
html part
<div id="ProductCode"><span>Product number</span><span class="link">2100022</span></div>
Upvotes: 0
Reputation: 133413
You can iterate elements compare its Node.nodeType, If node is TEXT_NODE(3)
. Then use .replaceWith() to replace the text node with anchor element
$('#ProductCode').contents().each(function () {
if (this.nodeType == 3) {
var elem = $('<a>', {
href: "http://www.example.com/" + this.nodeValue,
text: this.nodeValue
});
$(this).replaceWith(elem);
}
});
.wrap() is better option
$('#ProductCode').contents().each(function () {
if (this.nodeType == 3) {
var elem = $('<a>', {
href: "http://www.example.com/" + this.nodeValue
});
$(this).wrap(elem);
}
});
Upvotes: 5
Reputation: 530
Try this code:
$(document).ready(function(){
var span_text = $('#ProductCode span').text()
$('#ProductCode span').remove();
var year = $('#ProductCode').text()
$('#ProductCode').html('<span>'+ span_text +'</span><a href=”http://www.site.com/”' + year + '>' + year +'</a>');
})
You can check it also here: http://jsfiddle.net/aaa_borza/5nA9J/8/.
Upvotes: 0