Sourajit Sourajit - 1 year ago 88
Ajax Question

Find Class in javascript variable

I am using AJAX to get the HTML DOM of another page and then storing it within a variable like this

var doc=xhr.responseText;

Since the HTML is stored within the doc variable, I am using it to search for the class ,but it is throwing an error :

Uncaught TypeError: doc.getElementsByClassName is not a function

How to fix this,that is how can I use that variable to search for the class stored in it?

Answer Source

You are applying getElementsByClassName on a string (xhr.responseText is a string) it will only work with dom object not with string.

So instead what you can do is, create a temporary dom element object using document.createElement with the HTML content and get element inside.

var temp = document.createElement('div');
temp.innerHTML = xhr.responseText;
var list = temp.getElementsByClassName("Cname");

var temp = document.createElement('div');
temp.innerHTML = '<div class="Cname">a</div><div class="Cname1">a</div><div class="Cname">a</div>';
var list = temp.getElementsByClassName("Cname");


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download