View Full Version : Simply JavaScript - Question on hasClass

05-09-2019, 12:33 PM
I am trying to work some of the illustrated examples to get a better feel on how they function. Presently I am having trouble with a portion of the hasClass from page 88.

I retyped the code to be a simple function:

function has(target, theClass) {

var pattern = new RegExp("(^| )" + theClass + "( |$)");

if (pattern.test(target.className)) {
return true;

return false;

then in a html doc I have this:

<body onload='has("h3", "red");'>

<p class="red">I should be white background black text</p>
<h7>no class</h7>
<h3 class="red">Some class</h3>


If I understand correctly I thought target.className would get the class name of the element passed to it, thus I expected to have the function return True, but I consistently get False. I got False whether I put in an element with the class or without it. I then put the alert(target.className) in to see what the value was showing has and I get "Undefined". So presently I am not sure if I am doing something incorrect or it maybe that I don't have a proper understanding of className. Any help would be appreciated.
Thank you.

05-10-2019, 08:07 PM
Umm for my hasClass function i do something like this

return instance.classList.contains(name);
instance = element
name = what class you are looking for.