简体   繁体   中英

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.

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();

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();

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()

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM