JQuery: AddClass

I have a list where SPANs contains a number. I want to "copy" this number in STYLE (set the width as a percentage number) on the SPAN next to it.

HTML

<span class="celebName">Per</span>
<span class="celebPct">32</span>
<span class="celebBar"></span>

JQuery

$('.celebPct').each(function(index) {
    var celebPct = $(this).val();
    $(this).next(".celebBar").css({"width": + $(celebPct)+"%";});
});

I want the result to be like this:

<span class="celebName">Per</span>
<span class="celebPct">32</span>
<span class="celebBar" style="width:32%;"></span>

Why is this not working?

+3
source share
5 answers

Try the following:

$('.celebPct').each(function(index) {
    var celebPct = $(this).text();
    $(this).next(".celebBar").css({"width":  celebPct+"%"});
});

Here is a working fiddle: http://jsfiddle.net/maniator/beK89/

Also, if you have only one css change, you don't need the object in the call .css, you can just do:.css("width", celebPct+"%");

+3
source

Spaces don't matter, so try the text:

var celebPct = $(this).text();
+1
source

val() , text(). css . . text() , jQuery, jQuery .

$('.celebPct').each(function(index) {
    var celebPct = $(this).text();
    $(this).next(".celebBar").css( "width", celebPct+"%" );
});
+1
  • use text()not val()to get the inner text of the div. val for input
  • No need to wrap received celebPctin jquery
  • you had some strong syntax errors in the hash passed in css

cleared:

$('.celebPct').each(function(index) {
   var celebPct = $(this).text();
   $(this).next(".celebBar").css({"width": celebPct+"%"});
});
+1
source

This seems wrong:

var celebPct = $(this).val();

use

$(this).html()

instead, because span dont don't have .val just for input / selection.

so this should be the code:

$('.celebPct').each(function(index) {
    var celebPct = $(this).html();
    $(this).next(".celebBar").css({"width": celebPct + "%";});
});

no need to use $ (celebPct) since celebPct is not a jquery element

+1
source

All Articles