0

I'm getting 'cars' array using xmlhttprequest and dynamically creating the anchor tags for each value in the array.

Now im not able to access the innerhtml of newly created anchor tags.

//script for getting array and creating anchor tags dynamically

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {      
var cars = JSON.parse(xmlhttp.responseText);
for (i = 0; i < cars.length; i++)
{
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href','#');
aTag.setAttribute('class','cl');
aTag.innerHTML = cars[i] + "<br>";
mydiv.appendChild(aTag);
}

}
};

xmlhttp.open("POST", "http://localhost:3000/welcomepage", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();


//script for accessing innerhtml of the above created anchor tags.

$('.cl').click(function(e) {
e.preventDefault();
var t = $(this).text();
alert(t);
}
Black Heart
  • 649
  • 1
  • 7
  • 19

1 Answers1

0
  1. use $.post instead of XMLHttp
  2. use delegation In jQuery, how to attach events to dynamic html elements?
  3. note how I use $.each
//script for getting array and creating anchor tags dynamically
// not tested but should be ok depending on return values

$.post("http://localhost:3000/welcomepage", function(cars) {

  var $mydiv = $("#myDiv"),
    carHTML = [];
  $.each(cars, function(car) { // or function(_,car) - not clear from question
    carHTML.push($('<a/>', {
      'href': '#',
      'class': 'cl'
    }).html(car));
  });
  $mydiv.append(carHTML.join('<br/>'));
});

//script for accessing innerText of the above created anchor tags.

$("#myDiv").on("click", ".cl", function(e) {
  e.preventDefault();
  var t = $(this).text();
  alert(t);
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236