Search code examples
javascriptjquerywordpressif-statementshow-hide

jQuery if data-id element hasClass not working


I don't know if the function i am trying to create is missing an element or if I am missing something but my function isn't working at all. Not sure if am missing something or if i am not adding something. let me know I provided jQuery and screenshot of the code i am trying to get to work. Basically what i am trying to do is if a certain element that has a data-id has a certain class then hide certain list-items.

$(function($){
    if( $('.chbs-vehicle[data-id="313"] a').hasClass('chbs-state-selected') ){
        $('ul.chbs-list-reset li(1)').hide();
    }
});

enter image description here


Solution

  • li(1) isn't a valid expression and you should use a different evaluator:

    $('ul.chbs-list-reset li:eq(0)')
    $('ul.chbs-list-reset li:first-child')
    $('ul.chbs-list-reset li').eq(0)
    

    Take a look at this Demo

    If your condition is met on page load, it works just fine. However, if the chbs-state-selected class is added dynamically, you need to listen for that change with an event handler. Your script as you have it doesn't constantly poll the document to see if Vehicle 313's a has the class.

    Based on your comment, it sounds like you need to listen for that same click event that adds the chbs-state-selected class. Check out this rudimentary Demo.

    Given this, you don't necessarily need to check for the class, just attach the hide/show functions to the same event. However, if necessary you can add the hasClass check to it.

    Regardless, it should be inside that same handler that adds the chbs-state-selected in the first place