santa
santa

Reputation: 12512

Check if style="height: 0px"

I have a few elements with inline styling height assigned via a script. I need to check is an element has the following: style="height: 0px"

<div class="myEm" style="height: 30px">...</div>
<div class="myEm" style="height: 10px">...</div>
<div class="myEm" style="height: 0px">...</div>

jQuery

$(".myEm").each(function(){
   if ($(this).attr("style") == "0px") {
      $(this).css("border-color", "red");
   }
});

https://jsfiddle.net/p9nfskeL/1/

Upvotes: 2

Views: 1628

Answers (3)

Mr. Alien
Mr. Alien

Reputation: 157384

If that's the exact code you have and you cannot modify any HTML, than you can do a string comparison here..

$(".myEm").each(function() {
  if (this.style.height == '0px') {
    $(this).css("border-color", "red");
  }
});

The issue is, you have set min-height to 10px which is in action, so though you have 0px defined as inline, it won't override your CSS as min-height is defined separately. So either you need to call min-height: 0; inline or you can check like above. Note that the .height() will always return 10 so am using this.style.height to get the value you have declared inline and not the one which is being rendered.

Demo


Note that if the HTML is exact as you've shared, you can also achieve the above like

.myEm[style="height: 0px"] {
  border: 1px solid red;
}

Demo

Upvotes: 1

Avanthika
Avanthika

Reputation: 4182

  1. Your height is never 0 because you have min-height: 10px in your css.
  2. You can directly use $(this).height instead of accessing the style object. It gives a numeric value and you can do a NOT check as shown.

Hope this is helpful!

$(".myEm").each(function() {
  console.log($(this).height())
  if (!$(this).height()) {
    $(this).css("border-color", "red");
  }
});
.myEm {
  border: 1px solid #ccc;
  line-height: 20px;
  margin: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myEm" style="height: 30px">...</div>
<div class="myEm" style="height: 10px">...</div>
<div class="myEm" style="height: 0px">...</div>

Upvotes: 1

rupindr
rupindr

Reputation: 614

Following works:

$(".myEm").each(function() {
  if (this.style.height == "0px") {
    $(this).css("border-color", "red");
  }
});

Upvotes: 2

Related Questions