简体   繁体   中英

Inject anchor tag around existing text with JQuery

I have some HTML on a page that reads as follows:

<h3 class="ms-standardheader"><a name="SPBookmark_History"></a>History</h3>

I am running some javascript in the page READY where I am creating a dynamic hyperlink and I would like that to be inserted so that when the page renders the final result is:

    <h3 class="ms-standardheader"><a name="SPBookmark_History"></a><a href="https://thissite.com/newurl" target="_blank"> History</a></h3>

The class name of the H3 exists on multiple page elements. The Name of the anchor tag, SPBookmark_History, is unique.

How can I accomplish this using JQuery or straight javascript?

Thank you

Just follow below code:

$(document).ready(function(){
  var link = $('a[name=SPBookmark_History]');
  link.attr('href','https://thissite.com/newurl');
  link.attr('target','_blank');
});

JSFIDDLE SAMPLE

You can use:

The code:

 $('a[name="SPBookmark_History"]').closest('h3.ms-standardheader') .contents(). filter(function (idx, ele) { return ele.nodeType == Node.TEXT_NODE }) .wrap($('<a/>', {href: "https://thissite.com/newurl", target: "_blank"})); console.log('Result is: ' + document.getElementsByClassName('ms-standardheader')[0].outerHTML); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3 class="ms-standardheader"><a name="SPBookmark_History"></a>History</h3> 

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