简体   繁体   中英

Get specific text from a div and make into a link

I'm not sure if this is possible, I've been trying with jQuery but haven't got far.

I want to get the text from inside a div and turn them into links.

The problem is that I want the 3 names to become separate links eg href="/staff/john", href="/staff/sarah" and href="/staff/mike"

any help would be much appreciated.

 <div id="container"> john, sarah, mike </div>

Like this - no jQuery needed

 const container = document.getElementById("container"); container.innerHTML = container.textContent.split(",").map(name => `<a href="/staff/${name.trim().toLowerCase().replaceAll(" ","-")}">${name.trim()}</a>`).join(", ")
 <div id="container"> John Doe, Sarah Doe, Mike Hunt </div>

but if you want jQuery you can do

 $("#container").html(function() { return $(this).text().split(",").map(name => `<a href="/staff/${name.trim().toLowerCase().replaceAll(" ","-")}">${name.trim()}</a>`).join(", ") })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> John Doe, Sarah Doe, Mike Hunt </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