Reputation: 58412
I am trying to test the type of content in an element using javascript / jquery but whenever I get the content out of the element, it is always returned as a string:
$('.test').each(function() {
console.log(
this.innerHTML.trim(),
typeof this.innerHTML,
typeof $(this).text(),
$.type(this.innerHTML.trim()),
Number.isInteger(Number(this.innerHTML.trim()))
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
1234
</div>
<div class="test">
22.54
</div>
<div class="test">
2test
</div>
Is there a way to test the type without using typeof
so that I can parse the numbers so I can do a sort on them properly, rather than sorting them as strings
Upvotes: 1
Views: 72
Reputation: 138
You can for instance use function isNaN
to check if text (it also accepts strings) is not a number. If it's number parseFloat
or +
sign to parse your variable to desired type.
$('.test').each(function() {
var text = $(this).text();
if(!isNaN(text))
text = +text;
console.log(text + " " + typeof text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
1234
</div>
<div class="test">
22.54
</div>
<div class="test">
normalText
</div>
Upvotes: 1
Reputation: 4246
This is check func for typeof :
$('.test').each(function() {
var checktype = isNaN( this.innerHTML )
if (checktype == false) { alert("number"); return;}
else {
alert( typeof this.innerHTML )
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
1234c
</div>
<div class="test">
22.54
</div>
Upvotes: 1
Reputation: 22323
Use parseInt
before check isInteger
.
$('.test').each(function() {
console.log(Number.isInteger(parseInt(this.innerHTML.trim())))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
1234
</div>
<div class="test">
22.54
</div>
Upvotes: -1