3

HTML goes like this:

<span class="someClass position1" >span1</span>
<span class="someClass" >span2</span>
<span class="someClass" >span3</span>
<span class="someClass position2" >span4</span>
<span class="someClass" >span5</span>
<span class="someClass position4" >span6</span>
<span class="someClass position10" >span7</span>
<span class="someClass" >span8</span>
<span class="someClass position12" >span9</span>

Now, using jQuery, how will I change the backgroundColor of only those elements which have the class position+SomeINTEGER?

I want to select all the elements with the class poistion+TheRespectiveInteger

Navneet Saini
  • 934
  • 4
  • 16
  • 33

8 Answers8

6

I'm assuming you want to change the background of all the elements that have a class matching that pattern - not just for one particular number.

There is probably a hacky way to do this by treating class as just another attribute and doing a partial match against the value.

However a better solution is to add another class that you can select on. Perhaps have whatever is adding the positionX classes also add a positioned class at the same time.

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
  • 3
    As an extra : if you use a `positioned` class, you can simply use the css stylesheet to set the background color. – LeGEC Jun 21 '13 at 07:08
4

Try this:

$('.someClass').filter(function () {
    return /(\s|^)position[0-9]+(\s|$)/.test(this.className);
}).css('background-color', 'silver');

Working Fiddle

You can just modify the regex to get the perfect result :)

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • I'd also suggest adding a class instead of setting the background color directly. – jcsanyi Jun 21 '13 at 07:12
  • What about `position12`? What about `position1A`? – John Dvorak Jun 21 '13 at 07:26
  • @JanDvorak I just gave idea to OP. he/she can update the regex to get the perfect result. I mentioned this in the post. :) – Mr_Green Jun 21 '13 at 08:03
  • 1
    @Mr_Green hack in the sense of using the wrong tool (regex, instead of adding a class) – John Dvorak Jun 21 '13 at 08:06
  • @Mr_Green It's probably the best way of answering the questions as written - but it's still treating `class` as just an attribute and doing a text match against it, instead of using classes as they were intended. – jcsanyi Jun 21 '13 at 08:09
2
$(".someClass").each(function(){
    var classes = $(this).attr('class').split(/\s+/);
    for (var i = 0; i < classes.length; ++i)
    {
        if (classes[i].match(/^position\d+$/i)) {
            $(this).css('background-color', 'red');
        }
    }
});

For any elements containing a class that is positionN where N is any integer as well as someClass class, if you must do this.

http://jsfiddle.net/ysUMs/2/

luiges90
  • 4,493
  • 2
  • 28
  • 43
1

Try the following selector:

$("span:regex(class, (\s|^)position[0-9]+(\s|$))").css("background-color", "Green");

For more reference, see Write a jquery selector to select a class with a certain pattern

For regex selector, you need to write following line of code:

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
    validLabels = /^(data|css):/,
    attr = {
        method: matchParams[0].match(validLabels) ? 
                    matchParams[0].split(':')[0] : 'attr',
        property: matchParams.shift().replace(validLabels,'')
    },
    regexFlags = 'ig',
    regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

this wonderfull implementation given by James Padolsey.

see working example : http://jsfiddle.net/Q7fTW/16/

Community
  • 1
  • 1
Sanjeev Rai
  • 6,721
  • 4
  • 23
  • 33
  • 2
    I can't see any `:regex` selector in the jQuery documentation. That answer you linked refers to a specific plugin that needs to be included before this can be used: http://james.padolsey.com/javascript/regex-selector-for-jquery/ – John Dvorak Jun 21 '13 at 06:50
  • You need to include defination for `regex` selector. See my edited code. – Sanjeev Rai Jun 21 '13 at 06:57
  • 1
    I don't know enough about this custom regex selector to comment authoritatively, but I suspect this does not work as written. Why do you have a `.` if you're matching against the class attribute? How do you prevent selecting a `positioning` class? What happens if `position` is the first class in the attribute value? What about if it's not the first? – jcsanyi Jun 21 '13 at 07:03
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/32127/discussion-between-sanjeevrai-and-jcsanyi) – Sanjeev Rai Jun 21 '13 at 07:30
  • Having seen the plugin uses real regexes: no, that regex is not correct. – John Dvorak Jun 21 '13 at 07:34
  • @Jan Dvorak, in which scenario does it fails? – Sanjeev Rai Jun 21 '13 at 07:49
  • @SanjeevRai still wrong. `/position*/` matches `positio`, `position`, `positionnnnn` and such. This will find any element whose class list contains `positio` – John Dvorak Jun 21 '13 at 07:51
  • @SanjeevRai still wrong. `unposition1` and `position1A` will still test positive – John Dvorak Jun 21 '13 at 08:05
  • @Jan Dvorak, I don't have much idea of regular expression, can you modify the part of regular expression? – Sanjeev Rai Jun 21 '13 at 08:21
0
$(".position" + someINTEGER).css('backgroundColor','your color');

EDIT:

The way you asked the question is quite confusing.

To identify the elements which have a class position + Integer, you need to specify another class to them for identification

<span class="someClass integerclass position1" >span1</span>
<span class="someClass integerclass position2" >span4</span>

$(".integerclass).css('backgroundColor','your color');
Mandeep Jain
  • 2,304
  • 4
  • 22
  • 38
0

You can also try this:

<script type="text/javascript">
    $(function(){
        if( $(".someClass").hasClass(".position"+NUMBER) ){
            $(this).css({ 'backgroundColor','your color' });
        } 
    });
</script>
Nil'z
  • 7,487
  • 1
  • 18
  • 28
0

try this

it's working

    $('[class^="someClass position"]').css({ 'background-color': 'red' })
    //Selects elements that have the specified attribute with a value beginning exactly with a given string.

or

    $('[class*="position"]').css({ 'background-color': 'red' })
    //Selects elements that have the specified attribute with a value containing the a given substring.

or

    $('[class^="someClass"][class*=" position"]').css({ 'background-color': 'red' })
    //Matches elements that match all of the specified attribute filters.

refrence

http://api.jquery.com/category/selectors/attribute-selectors/

sangram parmar
  • 8,462
  • 2
  • 23
  • 47
  • 1
    This will also match anything with a `positioned` or `notpositioned` or `needsposition` class as well. – jcsanyi Jun 21 '13 at 07:18
  • Try anyone out of this as your requirement for solve this problem. – sangram parmar Jun 21 '13 at 07:41
  • The problem is there's no guarantee which order the classes will show up in in the attribute value when they're dynamically added/removed. That's in addition to the fact that you're not checking for numbers at all - these classes could be followed by anything, and they'd still be selected. – jcsanyi Jun 21 '13 at 07:42
  • Stll wrong. Option#1 is too specific (you can't swap the classes, add a new one to the beginning...) and also it matches `positioned` et al. #2 matches `positioned`, `unpositionable` et al. #3 breaks if the `positionX` class is first, and it also matches `positioned` – John Dvorak Jun 21 '13 at 07:43
  • But @Navneet Saini as per your problem one of this solution can solve it – sangram parmar Jun 21 '13 at 07:47
-2

If you know the value of SomeINTEGER then use :

  $(".position" + SomeINTEGER).css('backgroundColor','red');

else // This suggests starting from "position"

 $('span[class^=position]).css('backgroundColor','red');
SadhanaP
  • 37
  • 3
  • Your first solution doesn't actually answer the question - they **don't** know the integer. The second solution assumes that the position class is the first class that the element has - which can't be guaranteed. – jcsanyi Jun 21 '13 at 06:52