Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

wrapping a span tag with an a tag with a href target same as the text of the span

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance

>Solution :

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading