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 can I add ajax get call to a html element?

So I am trying to run a js code that turns all of <a></a> elements under another element <b></b> (the actual name is unique in the HTML) to a link that makes an HTTP get request. This is what I got and it doesn’t do anything.

$("b a").each(function(index, element) {
  var data = element.getAttribute("data-something");
  // $.ajax("https://example.com/" + data);
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<b data-something="an-id" class="missing">has has not been installed. to see more click on<a>Link</a></b>

>Solution :

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

First, the data- attribute is not on the a element, but on the b element. So on link click, you need to get the data from the parent.

Second, you need an event handler on the link.

$("b a").each(function(index, element) {
  let data = element.closest("b").getAttribute("data-something");

  $(element).on("click", function() {
    console.log(data)

    // Commented out for this snippet only
    //$.ajax("https://example.com/" + data);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<b data-something="an-id" class=\ "missing\">has has not been installed. to see more click on this <a>Link</a></b><br>
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