Home » Jquery » javascript – Getting value in div and changing to a link-Exceptionshub

javascript – Getting value in div and changing to a link-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a div that gets values from the database and prints them inside a div:

<div class="number-string">
123456789
</div>

I’m hoping to pull that value inside .number-string and change that div to a link where the href would be “https://somelink.com/123456789
All I have right now is

var getnumber = $('.number-string').text()

I can’t figure out how to change that div and add in a variable to a link

How to&Answer:

You can use the replaceWith() method to replace the div with a link.

$('.number-string').each(function(){
  $(this).replaceWith(`<a href="https://somelink.com/${this.innerText}">${this.innerText}</a>`);
})

Answer:

var trackingNum = $(".number-string");
function toLink(elem,link){
  let l1 = elem.text();
  elem.replaceWith(`<a href="${link}/${l1}">Click here</a>`);
}
toLink(trackingNum,'http://example');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number-string">
123456789
</div>