简体   繁体   中英

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)

Thank you in advance

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()
})

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM