Dashboard

How to call hide on return value from jquery select

My DOM structure looks like this:

  <div class="weather-Dashboard"></div>
    Dashboard
    <div class="weather-Charts">
      charts
    </div>
    <div class="weather-Statistics">
      Statistics
    </div>
    <div class="weather-Sites">
      Sites
    </div>

      

I want to select every div

dom whose class contains weather

and hide them using jQuery. Below is the JS code:

var e = $('div[class *= "weather"]');
e.each(function() {
  console.log(this);
  this.hide();
});

      

After running this code, I got below error:

Uncaught TypeError: this.hide is not a function

Seems to be this

not a jQuery object. What's wrong with my code? I have tried, if only the DOM request matches the request, I can call e.hide()

to hide the dom. However, this does not work for the case where there are multiple DOM matches.

+3


source to share


3 answers


The problem is with the this

DOMElement, which has no method hide()

. First you have to wrap this

in jQuery object:

var e = $('div[class*="weather"]');
e.each(function() {
  $(this).hide();
});

      



However, you should note that you don't need a loop here each()

- you can call hide()

directly on the collection:

$('div[class*="weather"]').hide();

      

+5


source


Internally, a each()

method this

refers to a DOM object and hide()

is a jQuery method, so you need to convert it to a jQuery object.

$(this).hide();

      



Or just update the style property display

.

this.style.display = 'none';

      

+1


source


var e = $('div[class *= "weather"]');
e.each(function() {
  $(this).hide();
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="weather-Dashboard"></div>
      Dashboard
  <div class="weather-Charts">
    charts
  </div>
  <div class="weather-Statistics">
    Statistics
  </div>
  <div class="weather-Sites">
    Sites
  </div>
      

Run code


+1


source







All Articles