Arunesh
Arunesh

Reputation: 297

How to get the value of span from jquery

I am trying to get the value of span from jquery but it shows an errir like this

   TypeError: document.getElementById(...) is null
   http://localhost:10489/YellowPages/YellowPageHome.aspx?Menu=menu_cat_3594
   Line 328

I have a span like this

     <div  class="RatingAggregate" style="height: 25px; width: 25px;  margin: 5px;">
       <span id="AvgRt_1<%#DataBinder.Eval(Container, "DataItem.BusinessID")%>">
        <%#DataBinder.Eval(Container, "DataItem.Rating")%></span>
     </div>

I want to get the value of span like this

       var averageRatingValue = document.getElementById('AvgRt_1').innerHTML;

But shows the null error. hOw can i do this as i am trying to learn the jquery.

Upvotes: 1

Views: 1326

Answers (4)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You are doing wrong exactly

var averageRatingValue = document.getElementById('AvgRt_1').innerHTML;

Because you have not the id AvgRt_1 but it is AvgRt_1<%#DataBinder.Eval(Container, "DataItem.BusinessID")%>

So, try this jquery:

var averageRatingValue = $('span [id^=AvgRt_1]').html();

with javascript:

//define var for that
var spanId = '<%#DataBinder.Eval(Container, "DataItem.BusinessID")%>';
var averageRatingValue = document.getElementById('AvgRt_1' + spanId).innerHTML;

Upvotes: 1

jbarnett
jbarnett

Reputation: 984

Why don't you just put the <%#DataBinder.Eval(Container, "DataItem.BusinessID")%> in a class?

Then you can do:

var businessId = '<%#DataBinder.Eval(Container, "DataItem.BusinessID")%>';
$('#AvgRt_1.' + businessId).text();

Upvotes: 2

Abhitalks
Abhitalks

Reputation: 28437

Firstly, your span has an id which concatenates the dataitem's businessID:

<span id="AvgRt_1<%#DataBinder.Eval(Container, "DataItem.BusinessID")%>">

So the Id would look like: AvgRt_1x where x is your BusinessID

Secondly: you are not using jQuery as you mentioned. Just pure Javascript.

var averageRatingValue = document.getElementById('AvgRt_1').innerHTML;

Thirdly, you will have to specify the correct id either by way of hardcoded value if you know the exact id beforehand, or by way of a variable:

$('#AvgRt_1' + variable).text();

Upvotes: 2

Satpal
Satpal

Reputation: 133453

You can simply get it like, you can also use Attribute Starts With Selector [name^="value"]

 $('span[id^="AvgRt_1"]').text() or or $('span').html()

For Particulr span

 $('span #SPANID').text()

Upvotes: 1

Related Questions