cbtr cbtr - 1 month ago 5
HTML Question

How to add a span inside a link tag with jQuery?

I have this code here in HTML:

<a class="cta" href="URL" target="_blank">TEXT</a>


What I try to achieve is to add a
span
tag inside the link tag, so that it would look like this:

<a class="cta" href="URL" target=_"blank"><span>TEXT</span></a>


I tried with prepend but it seems not to work for my caseā€¦

Answer

The .html( function ) is a good method for changing html content of element. Current html content of element setted in html variable in function that you can set it in new added child.

$("a.cta").html(function(i, html){
  return "<span>"+ html +"</span>";
});
span { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cta" href="URL" target="_blank">TEXT</a>
<a class="cta" href="URL" target="_blank">TEXT 2</a>