6

How do I get a number inside a div and use it as a number in JavaScript/jQuery? Here is what I have:

HTML:

<div class="number">25</div>

jQuery:

var numb = $('.number').val();
console.log(numb);

jsfiddle: http://jsfiddle.net/nw9rLfba/

amiry jd
  • 27,021
  • 30
  • 116
  • 215
Chipe
  • 4,641
  • 10
  • 36
  • 64

2 Answers2

21

.val() is for getting the value of form elements like input, select, etc. You can't use it on divs. You can use .text() to get the text content of the div element.

var number = $('.number').text();

But it will return the content as a string. To convert it to a Javascript number, you have to use parseInt():

var number = parseInt($('.number').text());
Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32
  • what if the element is a mixture of characters and a number. And I want to extract the number only. If we apply your code the outcome is NaN. – Dr. Younes Henni Nov 09 '17 at 11:39
  • @Dr.YounesHenni I agree, my code only assumes that the content of the element are just numeric characters in which `parseInt` would work. But it shouldn't be difficult to tweak to support your scenario. We could for example remove the non-numeric characters first before attempting to `parseInt` :) – Arnelle Balane Nov 10 '17 at 05:47
  • Yes. In my case I added a span around it and applied your method. Works perfectly. – Dr. Younes Henni Nov 10 '17 at 08:35
5
var numb = $('.number').text();
console.log(parseInt(numb));
Wojciech Mleczek
  • 1,574
  • 15
  • 18