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

笑着哭i 提交于 2021-02-11 06:31:08

问题


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.


回答1:


You can use .wrapInner()

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


来源:https://stackoverflow.com/questions/27782861/how-do-i-wrap-text-within-a-link-tag-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!