How to Create a Script to Automate Link Exchange in Html?

I'm performing maintenance on a system that has hundreds of links on one page as follows:

<li> Revista alvo <a href="">  </a> </li>

Note that there is text outside the a tag. What I want to do, put this text inside the a tag with your supposed href, the example above would look like this:

<li> <a href=""> Revista alvo </a> </li>

I'm doing this change in hand but there are hundreds and hundreds of links, which makes the task tiring. Does anyone have any idea how I can script to do this? It can be in any language, PHP,JS etc.

8

1 Answer

As you regarded, the text is HTML format, so you can easily, edit the HTML file and use to apply changes to the like the following:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src=""></script>


</head>
<body>
<ul id="linksList">
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>
  <li> Revista alvo <a href="">  </a> </li>

  </ul>
  <a href="#" id="changeIt">Change</a>
  <script>
    $(document).ready(function(){     
      $("#changeIt").click(function(){
        $("#linksList li").each(function(){
          txt = $(this).text().split(' )[0].trim();
          lnk = $(this).children('a').text(txt)
          $(this).html(lnk)
        })
      })
    })
  </script>
</body>
</html>

The edit should include,

  1. include jquery
  2. give the ul or ol that contains the li an id
  3. use the code supplied in the latter script tag which consider the given id to the list is linksList
  4. HTML link with id changeIt to invoke the code.

This is an Online demo

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest