How to extract number from HTML range using jQuery?

Using jQuery, I would like to extract the number from <span>and use it to calculate the new value.

<div class="post-100" data-postid="100">
   <span class="score">3</span>
</div>

I have a general idea, but I cannot figure out how to refer to an existing range value:

if (response.newvoteid == null)
{
    $(".post-" + $(this).data("postid") + " .score").text(
            parseInt( **EXISTING VALUE + 1 OR -1**));
}

Update: Now I use the following, which cannot calculate the new value, but just adds the number to the text. For example, <span class="score">3</span>it becomes<span class="score">31</span>

var number = $(".post-" + $(this).data("postId") + " .score").text();
$(".post-" + $(this).data("postId") + " .score").text(number + 1);
+3
source share
4 answers

Just pass a function .text()that returns the old value, increased (or decreased):

$(".post-" + $(this).data("postid") + " .score").text( function( i, txt ) {
    return ( parseInt( txt, 10 ) + 1 ); // Returns the old value,
});                                     //      plus (or minus) 1.
+4
source

parseInt() - , , , :

parseInt($(".score").text())

, parseInt():

var newVal = parseInt($(".score").text()) + 1

, . ?

, .

+4
 <span class="score">3</span>

, , , ,

$(.score).text();

api

http://api.jquery.com/text/

3

+1
$(spanId).text();

/ span.

- :

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

, , , .

var intRegex = /^\d+$/;

var number = $(spanId).text();
if(intRegex.test(number)) {
 ...//proceed cuz it a number
}
0

Source: https://habr.com/ru/post/1779879/


All Articles