shanmugam s shanmugam s - 4 months ago 20
jQuery Question

How to get the text with in span tag using jquery?

I want get text within this span tag using its class:

<span id="prizevalue_g12" class="pull-right grid_val">£12</span>


I want to get
12
. I tried the below code:

var ex_price = $(".grid_val").html();


and

ex_price = $(".grid_val").html();

Answer

You can use replace() to remove £.

$(document).ready(function(){
  var ex_price = $(".grid_val").html();
  ex_price = $(".grid_val").html();  
  $("#solution").text(ex_price.replace('£', '') );
});

This is just a tought, but I think this would be a perfect place to use some custom data-attributes, like data-value. It would work nice especially if you have a lot of these values to get.

The outcome would be smthn like this:

<!-- HTML -->
<span class="grid_val" data-value="12">£12</span>
<span class="grid_val" data-value="15">£15</span>
<span class="grid_val" data-value="13">£13</span>
<span class="grid_val" data-value="1">£1</span>

<script>
$(".grid_val").each(function(){
  var value = $(this).attr("data-value");
  //do something with it
});
</script>