K
K
kimqar342534262021-06-08 14:28:41
JavaScript
kimqar34253426, 2021-06-08 14:28:41

JS how to correctly go through the elements by links and if the link matches the get add a class to it?

I do a check on the url get-parameter, and if the block contains this link, then I add a class to it

$('.navigation-list__item a').each(function() {
        var link = jQuery(this).attr("href");
        if (link === get) {
            (this).parentNode.addClass("navigation-list__item_active");
        }
    });

(get variable contains get parameter)
how to write this line correctly
(this).parentNode.addClass("navigation-list__item_active");

Now
throws Uncaught TypeError: this.parentNode.addClass is not a function

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergio, 2021-06-08
@kimqar34253426

Need to be replaced

(this).parentNode.addClass("navigation-list__item_active");

on the
$(this).parent().addClass("navigation-list__item_active");

and even better like this (more reliable, in case the navigation-list__item structure changes):
$(this).closest(".navigation-list__item").addClass("navigation-list__item_active");

parentNode is a property of DOM elements, in jQuery the equivalent method is parent()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question