Lonnie McGill Lonnie McGill - 1 month ago 5
Javascript Question

Can you use getElementByClassName to get a class you added with jquery?

Can you use getElementByClassName to get a class you added with jquery? I added a class with jquery but i can't seem to retrieve it using getElementByClassName. When I console log classList.value all I get is header. Yet when I console log classList i can see this:
enter image description here

Just curious if it is possible to target it. I tried to get classList.list(1) but it comes back as null.

Here is my code:

import React from 'react';
import jQuery from 'jquery';
import $ from 'jquery';

export default class ProjectsHeader extends React.Component {

constructor() {
super()
}

componentDidMount() {

let head = $(".header");
let stick = "sticky";

$(window).scroll(function() {
$(window).scrollTop() > 400
? head.addClass(stick)
: head.removeClass(stick)
})

let projHead = document.getElementById("projHead");




console.log(projHead.classList);
console.log(projHead.classList.value);

}

render() {
return (
<div id="projHead" className="header">
<div className="not-sticky-div">
<div>"This is My Projects Page" McGill</div>
</div>
<div className="hidden-span">
<span>Something1</span>
<span>Something2</span>
<span>Something3</span>
</div>
</div>
)
}
}

Answer

You can't see it in the console because you are logging it before you add the class.

You are adding the class when you scroll to a position greater than 400px, but you are logging the class list as soon as your component gets mounted. Try to move your console.log to your scroll event's callback.

Also remember that JavaScript events are asynchronous, so even if somehow they are triggered before your componentDidMount function finishes executing, your callback won't be called until the call stack gets empty.

Great talk about JavaScript's Event Loop: https://www.youtube.com/watch?v=8aGhZQkoFbQ

And off-topic advice: Try to get rid of jQuery if you are using React ;)