2

I have a div with a class which I need to switch out based on what the user is interacting with.

<div class="book-chapter-name chapter2" data-lhg="chapter-info">
    <span>Chapter String Here</span>
</div>

I have the current div in a jQuery object and this has been found using:

$('div[class*="chapter"]')

What I want to do is remove the existing class and insert a new class so that chapter2 becomes chapter3

var chapterString = $('#page'+page).attr('data-lhg-chapter'),
    chapterNumber = $('#page'+page).attr('data-lhg-chapter-number'),
    chapterInfo = $('[data-lhg="chapter-info"]');

if($('div[class*="chapter"]')){
    $('div[class*="chapter"]').removeClass('chapter[0-9]');
}

$(chapterInfo).text(chapterString).addClass('chapter'+chapterNumber);

This doesn't seem to work, I think it is to do with the string passed to removeClass but I am not sure what to put in there to get the right result.

Justin Erswell
  • 688
  • 7
  • 42
  • 87
  • 1
    Have a look at the second answer here: https://stackoverflow.com/questions/16039708/jquery-wildcard-class-selector-in-removeclass - use a function and regex to remove the class – StudioTime Sep 20 '17 at 12:42
  • 1
    The function `removeClass` looks in your case for css class 'chapter[0-9]' – Reporter Sep 20 '17 at 12:42

2 Answers2

2

You can remove all classes and add them back again with changed number.

$('div[class*="chapter"]').removeClass();

And then

$(chapterInfo).text(chapterString).addClass("book-chapter-name").addClass('chapter'+chapterNumber);
DobromirM
  • 2,017
  • 2
  • 20
  • 29
1
$('div[class^="chapter"]')
[attribute^=value]

div[class^="https"] Selects every <div> element whose class attribute value begins with "chapter"

Farhad Bagherlo
  • 6,725
  • 3
  • 25
  • 47