Home > Mobile >  How to Find a text in page and then add hyperlink to it using JS?
How to Find a text in page and then add hyperlink to it using JS?

Time:05-30

I am developing a Wordpress website and installed a theme. Some of the elements don't have the option to add hyperlinks to it, so I am trying to add hyperlinks or make the blocks clickable using JS.

I want to add hyperlinks to those li elements and theme currently doesn't support it.

My Logic:

  1. Search for the text in li once page loads.
  2. Add Hyperlink to it if text is found.
<div >
  <ul >
    <li>
      <i ></i> abcd
    </li>
    <li>
      <i ></i> efgh
    </li>
    <li>
      <i ></i> Content Delivery Network
    </li>
    <li>
      <i ></i> 24/7 Hours services
    </li>
    </ul>
</div>

CodePudding user response:

There's a few ways to tackle this. If you're using jquery already you might want to take a look at the documentation for the .wrap() function: https://api.jquery.com/wrap/

If you're not using jquery, it's simple enough to do with plain js. You will first need to select all the <li> elements and then loop through them and replace the contents with your <a> tags one by one. You can do this by modifying the element's innerHTML property.

I will say this seems like a strange issue. There must be a way for you to add links to your content without resorting to this method. And you'll still need to figure some other problems out - how will you know where each link should go, for instance?

Anyway, here is a snippet so you can see the principle behind what you asked:

const items = document.querySelectorAll('li')
items.forEach((item) => {
  const children = item.innerHTML
  item.innerHTML='<a href="http://stackoverflow.com">'   children   '</a>'
})
<div >
  <ul >
    <li>
      <i ></i> abcd
    </li>
    <li>
      <i ></i> efgh
    </li>
    <li>
      <i ></i> Content Delivery Network
    </li>
    <li>
      <i ></i> 24/7 Hours services
    </li>
    </ul>
</div>

  • Related