Beata
Beata

Reputation: 31

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.

Upvotes: 3

Views: 166

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

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>

Upvotes: 3

symlink
symlink

Reputation: 12209

With jQuery:

$(function() {
  $("p").each(function() {
      $(this).addClass(isNaN($(this).text()) ? "number" : "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>

With regular Javascript:

document.querySelectorAll("p").forEach((el) => {
    el.classList += isNaN(el.textContent) ? "other" : "number"
})
.number {color: blue} .other {color: green}
<p>abc</p>
<p>123</p>
<p>dynia</p>
<p>semolina</p>
<p>ogór</p>
<p>234</p>
<p>2345</p>

Upvotes: 0

Related Questions