Home > Software engineering >  wrapping a span tag with an a tag with a href target same as the text of the span
wrapping a span tag with an a tag with a href target same as the text of the span

Time:05-11

my document has many span tags like the following:

<span class='myClass'>aaa</span>

I would like to turn each of them into the following:

<a href="http://www.example.com/aaa" onclick="myfunc();"><span class='myClass'>aaa</span></a>

Is there a way to do this? could be plain js or jquery (3.1.1)

Thank you in advance

CodePudding user response:

With jQuery, you can iterate all .myClass elements using .each(), then wrap them using .wrap()

$(".myClass").each( function() {
  $(this).wrap('<a href="http://www.example.com/'   $(this).text()   '" onclick="myfunc();" />');
});

console.log($(".myClass").parent())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<span class='myClass'>aaa</span>
<span class='myClass'>bbb</span>
<span class='myClass'>ccc</span>
<span class='myClass'>ddd</span>

https://api.jquery.com/wrap/

CodePudding user response:

Use this:

const els=document.querySelectorAll("span.myClass");
els.forEach((el)=>{
   const t=el.textContent;
   const aEl=document.createElement("a");
   aEl.href=`http://example.com/${t}`;
   aEl.appendChild(el.cloneNode(true))
   el.parentElement.insertBefore(aEl,el);
   el.remove()
})
  • Related