Matija Matija - 2 months ago 6
Javascript Question

Can't add class to element

I have problem that is unexplainable to me. I have a simple

<svg>
element with "normal" class-->
"small_circle_svg_menu"
. And I want to add a class
"animated"
to that element. I mean that's the simplest thing and I can't do it right but can do some much more complicated things.

Here's what I do to add a class to element. I tried to add class in two ways. First way is the simple function which checks if element has that class and if the element don't have it add's it to element.

The second way is the simplest thing ever(you'll see).

This is the first way:

This function adds class normally to any other element. I also logged the
document.getElementsByClassName('small_circle_svg_menu')[0]
to console to see if I'm maybe logging wrong element. (But that was not the case, I was logging right element).

function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

addClass(document.getElementsByClassName('small_circle_svg_menu')[0],"animated")


The second way:

document.getElementsByClassName('small_circle_svg_menu')[0].className += "animated"


Element in HTML is positioned in so I'll show you whole .

<header >
<div class=" menu_circle circles-div ">
<div class="icn__wrap menu " id="menu">
<i class="icn__hamburger state_1" id="icn__hamburger-1" ></i>
<i class="icn__hamburger state_1" id="icn__hamburger-2" ></i>
<i class="icn__hamburger state_1" id="icn__hamburger-3" ></i>
<svg class="small_circle_svg_menu " version="1.1" xmlns="http://www.w3.org/2000/svg" width="58px" height="58px" viewBox="0 0 16 16" preserveAspectRatio="none" >
<circle cx="8" cy="8" r="6.215" transform="rotate(90 8 8)" stroke="white" class="small-circle" id="menu_circle"></circle>
</svg>
</div>
</div>
<img id="logo" src="images/nolo.png" alt="nole.logo" onclick="fullpage.moveTo(1)"/>
<div class="page-title background_LG"id="prvinatpis" >Novak Djokovic</div>
<div class="page-title background_LG"id="drugastrananatpis" >News </div>
<div class="page-title background_LG"id="trecastrananatpis" >Tour </div>
<div class="page-title background_LG"id="cetvrtastrananatpis" >Story </div>
<div class="page-title background_LG"id="petastrananatpis" >Gallery </div>
</header>


Also I want to mention that I didn't get any error in console so far.First and only time I get error is when using first way. Then I get this error.

TypeError: ele.className.match is not a function.
(In 'ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'))', 'ele.className.match' is undefined)

Answer

At your element use the method classList.add().

var element = document.getElementById("my-class");
element.classList.add("class-name");

Search your prefer element with document.querySelectorAll.

Comments