Search code examples
javascriptfor-looponclicklistenertostringgetelementsbyclassname

How to convert srcElement into string in Javascript


I am using a for loop to add a onClick listener to my textboxes and when the user clicks the textbox it gets its ID.

What I want to do is convert the ID that I am getting into a string because there are some task that require me to use string and not ID.

var textbox = getElementsByClassName("myTextbox");
var textboxID = null;

    for (var i = 0; i < textbox.length; i++) {

        textbox[i].addEventListener("click", function(listener) {
             textboxID = listener.srcElement;
            });
}

I have tried: textboxID = listener.srcElement.toString(); and textboxID.toString() but had no luck.

Any help is welcomed.


Solution

  • Use the id property of the object that srcElement refers to:

    textboxID = listener.srcElement.id;