Hide specific HTML element if screen is smaller than 767px (jQuery)

On one of my websites I want to remove a specific HTML element if the screen is smaller than 767px (on mobile devices).

The following piece of HTML is used 9 times on the page:

<div class="price-list__item-desc">&nbsp;</div>

So all 9 pieces of HTML have to be removed only on mobile devices.

I already included the following jQuery file on the website:

jQuery(function ($) {
    if (window.matchMedia('(max-width: 767px)').matches) {
        $('<div class="price-list__item-desc">&nbsp;</div>').hide();
    }
    else {
        $('<div class="price-list__item-desc">&nbsp;</div>').show();
    }
});

However, the code is not working and the pieces of HTML still show up on mobile devices. I know there might be a very easy fix for this particular objective. But after searching the internet for two days I have come across so many different options that actually made me more confused.

Would very much appreciate any help, thanks in advance!


In the first method, when the page width changes, the div.price-list__item-desc element is hidden or shown using jQuery by controlling the page width.

In the method you developed, the anonymous function is not run to hide the item when the page changes; you need to use event handler method. In the structure I developed, the onresize event is affected when the page width changes. This way I can catch this event when the page width changes.

$( document ).ready(function() {
  window.onresize = function() {  
    console.log(`Width: ${$( window ).width()}`);
    var divs = document.querySelectorAll("div.price-list__item-desc");
    
    if (window.matchMedia('(max-width: 767px)').matches)
    {
        $('div.price-list__item-desc').removeClass("active");
      
        for (var i = 0; i < divs.length; i++) 
        {
          if(divs[i].innerHTML === '&nbsp;')
            divs[i].style.display = "none";
          else
            divs[i].style.display = "block";
        }
    }
    else
    {
      $('div.price-list__item-desc').addClass("active");
    }
  }
  
  window.onresize();
});
div.price-list__item-desc {
  background-color: red;
  display: none;
}

.active{
  display: block !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="price-list__item-desc">&nbsp;</div>
<div class="price-list__item-desc">1</div>
<div class="price-list__item-desc">&nbsp;</div>
<div class="price-list__item-desc">2</div>
<div class="price-list__item-desc">&nbsp;</div>