Class selector is not working in JS

Hi there

this is my jsfiddle

When I am clicking on button I want to change text of above 2 class but that is not working

How can I acheive this?

getElementsByClassName() returns an array-like struct of objects, not an object. Iterate through the array, changing each.



Plus you had userNum and userNam…typo on the names of things. Check your old fiddle to see you weren’t actually referencing properly.

Plus event handlers like onClick are 10+ years old. 100% of the time, use event listeners like I did.

var userNam=document.getElementsByClassName('userName');
    userNum.innerHTML="This is Changed Text";

See how those names don’t match? Not an issue in my updated code though…

1 Like

Thanks to both of you

updated jsfiddle

Working fine

No! Please follow mine. Do not use onClick! Bad! :frowning: . Say “NO” to event handlers (onClick, etc)!

:cold_sweat: :scream:

I don’t know that type of event handling exists in javascript usually I use this way in android or java swing

You see how in the HTML you do onclick=“changeValues()”?

That’s an event handler. You are modifying hte HTML to add the function.

Think of it like this. Whenever you write Javascript, DO NOT TOUCH THE HTML. That means do not add attributes like onclick=“changeValues()”. Instead, do what I did where I do addEventListener() which does the SAME THING but does not mess with the HTML (bad for many reasons.)

I do not want to see you get into bad habits (aka event handlers.)

1 Like

Okay… I’ve not heard this, before. Just curious: Why is it considered bad?



IMHO the main problem is maintainability
Same as “in the tag CSS”

Much easier to tweak and debug if you don’t have JS and CSS scattered about in your mark-up.

TBH, I sometimes do this during development, but once I think everything is OK out it goes.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.