Reputation: 103
I am trying to add a link to text using javascript and jquery. But when I tried it it will display [object Text] as the output. My attempt is as below.
var remId = $('#userId').text();
var a = document.createElement('a');
var linkText = document.createTextNode(remId);
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
a.id="fre";
document.body.appendChild(a);
$('#userId').text(linkText);
console.log(linkText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<div class="two">
<p id="userId">
abc
</p>
</div>
</div>
Here above linkText variable should display the value with text. So where could I get wrong?
Upvotes: 0
Views: 79
Reputation: 1571
You just have one issue with your approach. instead of using text
property, use html
property and pass your a
element.
$(function() {
var remId = $('#userId').text();
var a = document.createElement('a');
var linkText = document.createTextNode(remId);
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
a.id="fre";
document.body.appendChild(a);
$('#userId').html(a);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<div class="two">
<p id="userId">
abc
</p>
</div>
</div>
Upvotes: 0
Reputation: 5322
It is too simple with only jquery
$('#userId').html('<a href="http://example.com" title="my title tex" id="fre"> '+ $('#userId').text() + ' </a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<div class="two">
<p id="userId">
abc
</p>
</div>
</div>
Upvotes: 3