code578841441 code578841441 - 5 months ago 11
Javascript Question

Object doesn't support property or method 'text'

I get the error in the title when I call

setDefaultLocalPrinter()
. If I call the span b y its ID like this
$("#spanId").text("test")
then it works, but it doesn't work like below

<span id="defaultLocalPrinterName<c:out value="${entry.index}"/>">Printer</span>

function setDefaultLocalPrinter(printerName) {
console.log("setDefaultLocalPrinter: " + printerName)
$('span[id^="defaultLocalPrinterName"]').each(function(){
this.text(printerName)
});
}

Answer

Use $(this) inside each().

$(this).text(printerName);

this is plain JavaScript object. It cannot be used to call method which is defined on the jQuery prototype. $(this) is this wrapped in jQuery that have access to all the methods & properties defined on the jQuery prototype.

If you want to use plain JavaScript,

this.textContent = printerName;

each is not even needed, the textContent can be directly set using text() on selector.

$('span[id^="defaultLocalPrinterName"]').text(printerName);