Reputation: 148
I have the following code which I found at W3Schools and when I use document.getElementById
it works, when I change this to document.getElementsByClassName
(on my full code, I will have more than <p class="txthint">
why I thought I should be using documents.getElementsByClassName
) it just stops working.
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include file="Connections/PSCRM.asp" -->
<%
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_PSCRM_STRING
Recordset1_cmd.CommandText = "SELECT prodref FROM dba.proditem where created >= '2015-08-01' and obsolete = '0' ORDER BY prodref asc"
Recordset1_cmd.Prepared = true
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="">
<input type="text" onChange="showCustomer(this.value)" value="">
</form>
<br>
<div class="txtHint">Customer info will be listed here...</div>
<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementsByClassName("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementsByClassName("txtHint").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "data.asp?prodref="+str, true);
xhttp.send();
}
</script>
</body>
</html>
<%
Recordset1.Close()
Set Recordset1 = Nothing
%>
Upvotes: 0
Views: 173
Reputation: 953
If you look at the documentation for getElementsByClassName, you'll notice that you are returning an array of object whereas getElementById returns a single element.
With the array, there is no prototype for innerHtml, this is only exposed on a single element.
What you will need to do is iterate through the list of elements you retrieve from the getElementsByClassName.
var elements =document.getElementsByClassName("txtHint");
for(var i = 0; i < elements.length; i++){
elements[i].innerHTML = xhttp.responseText
};
Try that and see if it helps
Upvotes: 1
Reputation: 32212
getElementsByClassName
returns a collection of nodes, not a single node. You need to iterate that collection and set the innerHTML
property on each node:
var nodes = document.getElementsByClassName("txtHint");
for (var i = 0; i < nodes.length; i++)
nodes[i].innerHTML = '';
Your current code is setting the property on the collection itself which, as it's perfectly valid JavaScript, doesn't error, but causes nothing to update either - it's just now the node collection has an unused innerHTML
property.
Upvotes: 3