Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a class for numbers

I add a class to paragraphs in regular statement:

$("p").each(function(i, elem) {
  typeof elem === "number" ?
    ($("p").addClass("number")) :
    ($("p").addClass("other"))
})
.number {
  color: blue;
}

.other {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>abc</p>
<p>123</p>
<p>dynia</p>
<p>semolina</p>
<p>ogór</p>
<p>234</p>
<p>2345</p>

But all elements are green (like not-numbers). If I instead of adding class type console.log(True/False) I obtain correct results.

like image 913
Beata Avatar asked Dec 04 '25 00:12

Beata


1 Answers

The type of elem is always object. You need the text content of elem, which you can get using jQuery's .text() method. However, the text content is a string, and you can use isNaN() to check if it can be converted to a number:

$("p").each(function(i, elem) {
  var $el = $(elem);
  $el.addClass(isNaN($el.text()) ? 'other' : 'number');
})
.number {
  color: blue;
}

.other {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>abc</p>
<p>123</p>
<p>dynia</p>
<p>semolina</p>
<p>ogór</p>
<p>234</p>
<p>2345</p>
like image 167
Ori Drori Avatar answered Dec 06 '25 14:12

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!