2

i've searcherd for answers but i didn't find nothing.. so please if you think this is a duplicate tell me and i'll remove it, thanks.

When i write something like body.classList.add("someExampleClass"); the console gives me that Uncaught TypeError: Cannot read property 'add' of undefined. I've added the CDN

//cdnjs.cloudflare.com/ajax/libs/classlist/2014.01.31/classList.min.js

but it keeps the error, i've tried with Chrome and Safari.

That's the full code:

HTML

  <svg height="35" width="35" id="rect1" class="" onmouseover="over()">
      <rect width="35" height="35"/>
  </svg>

JS

function over() {
  $('p').classList.add("purple");
}

Thanks in advance to all and have a good day.

2
  • You need $('p').addClass("purple") ? Jun 8, 2016 at 10:14
  • I do not see any p-tag in your HTML. When do you call your over() function? Maybe classList-js is not loaded yet?
    – Jurik
    Jun 8, 2016 at 10:15

2 Answers 2

3

You should try this:

$('p')[0].classList.add("purple");

or this:

$('p').addClass("purple");
1

classList is a DOM property. So your code should be,

$('p')[0].classList.add("purple");

Or

 $('p').get(0).classList.add("purple");

$('p') is a jquery object, get() will convert it as dom object.

Or you can simply use,

$('p').addClass("purple")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.