简体   繁体   中英

How do I wrap text within a link tag using JavaScript/Jquery?

Here is my current code:

<a class="mg_label_7" href="/" shape="">Hello</a>

I want to have:

<a class="mg_label_7" href="/" shape=""><div id="hello">Hello</div></a>

So I can manipulate the background of the link text without changing the rest of the link areas text. Is there anyway to pinpoint this piece of text and insert a div or even a span using JavaScript/jQuery?

I've been trying to do this for around 3 hours, the closest I've got to achieving it is using

  var elem = document.getElementsByTagName('a')[0]; var html = elem.innerHTML; elem.innerHTML = '<div class="red">'+ html + '</div>' 

which successfully targeted a link in my code and changed it to the span, but if I try to getElementsByTagName then getElementByClassName and use mg_label_7 it won't work. There are duplicates of the tag in the code and I want to target all of them.

I'm trying to manipulate a SharePoint web part so I'm not sure if it's stopping it from being edited.

您可以使用.wrapInner()

$('.mg_label_7').wrapInner('<div id="hello"></div>')

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