Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write the Javascript that gives each link a custom URL to jump to on click according to it's child element's text contents?

I wonder if it is possible to write a Javascript that gives each link a custom format URL to go to on click.

<!-- example set one -->
<a href="javascript:myfunction()" class="relative-url" target="_blank">
  <span id="input01">campfire<span>
  <span id="input02">red<span>
</a>
<!-- example set two -->
<a href="javascript:myfunction()" class="relative-url" target="_blank">
  <span id="input01">pepe<span>
  <span id="input02">green<span>
</a>

How to write the custom javascript to formulate an URL for each <a class="relative-url"> ?

<script>
 // use text content of child element id=input01 and id=input02 to 
 // formulate an URL for it's parent div or <a>
 // eg. https://www.example.com?type=campfire&color=red
 // eg. https://www.example.com?type=pepe&color=green
</script>

Any good idea? Thanks a lot~

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to do it at runtime, you could do something like this. I used jQuery since you tagged it in your question.

 $('.relative-url').each(function() {
      let type = $(this).find('.input01').text();
      let color = $(this).find('.input02').text();
      this.href = `https://www.example.com?type=${type}&color=${color}`
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- example set one -->
<a class="relative-url" target="_blank">
  <span class="input01">campfire</span>
  <span class="input02">red</span>
</a>
<br/>
<!-- example set two -->
<a class="relative-url" target="_blank">
  <span class="input01">pepe</span>
  <span class="input02">green</span>
</a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading