Lonnie McGill Lonnie McGill - 1 year ago 74
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() {

componentDidMount() {

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

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

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



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

Answer Source

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 ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download