anson920520 anson920520 - 6 months ago 20
HTML Question

JQuery: Getting number from html element and alter it in Jquery/Javascript

I have some number printed on my html for special usage, therefore i need to grab it from html, alter it in javascript and output again.

So i have few numbers like below in my HTML:

<p id="usage">6564</p>


and i'd like to have a if statment in order do some modifcation of "6564",
below is some pseudo codes, which tells what i'd like to do.

var checker = $("#usage").html();

if(checker >= 2 digits){
//display the first two digits
}
else {
$("#usage").html("1");
}


The if statement should display the first two digits only, if the number has more than 2 digits otherwise it will return "10", So the result should be "65"

Answer

var checker = $("#usage").text();

if(checker.length >= 2){
  $("#usage").text(checker.slice(0,2));
  
}
else {
  $("#usage").text("10");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="usage">6564</p>

  1. Use slice to get the 2 digits.
  2. Use length to tell if number has more than 2 digits