質問

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!

役に立ちましたか?

解決

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);
    }
});

DEMO

EDIT

.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);
    }
});

DEMO with wrap

他のヒント

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/.

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>

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);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top