0

I'm kinda stuck right now. I need to get a certain class from an element. The class attribute could look like:

<div class="span12 display">

or:

<div class="span24 overview overview-small">

So the span* is always the same just the number can differ.

I really don't know how to get the span* everytime using jQuery.

EDIT: My goal is to change the size of the element. e.g. from span12 to span18. It is possible that I need to change the size from span10 to span18 or from span8 to span18. That's why I'd prefer a generic solution.

So the number is quite random. And it's very important to know the span-number before changing it to span18 because it should be possible to change the previous size (span).

Sorry that I forgot to mention this. :|

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Andre Zimpel
  • 2,323
  • 4
  • 27
  • 42

3 Answers3

2

Simple string parsing can get it for you: http://jsfiddle.net/7sXFb/

$("div[class*=span]").each(function(){
  var cls = this.className,
      prt = cls.split(" "),
      spn = 0;

  for (var i = 0; i < prt.length; i++){
    if (prt[i].indexOf("span") > -1)
      spn = +prt[i].replace("span","");
  }

  console.log(spn);
});

You can add 10 like this:

this.className = this.className.replace("span" + spn, "span" + (spn+10));

Or, like so:

$(this).removeClass("span" + spn).addClass("span" + (spn+10));
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
1

If you have the number, it shouldn't be that hard.

var spanNumber = 15;
var spanSelector = ".span"+spanNumber;
var spanClassName = $(spanSelector)[0].className;

If you do not have the number, then you can look for a partial match and then do something with that group

var spans = $('div[class*=span]');

Perhaps iterate them:

demo: http://jsfiddle.net/hFx26/

spans.each(function(index,element){
 var spanClass = element.className;
 var tar = spanClass.indexOf("span");
 var number = "";
 for( var i = (tar + 4); i < spanClass.length; i++ ){
  if( spanClass[i] == " " ) break;
  number += spanClass[i].toString();
 }
 number = parseInt(number);
 //call some function with number, element, or replace the className
});
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

You could simply add another class like allspans to each element that has a span* value and use that as the selector.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103