-1

I want to replace the class name with just the id clicked. But the condition is, there is the beginning of the class name ("filter-") I want to change.

For example:

<div class="change filter-" id="changeMe"></div>
<div class="list">
     <div class="click" id="first"></div>
     <div class="click" id="second"></div>
     <div class="click" id="third"></div>
</div>

When you click #first then filter- must be filter-first like this:

<div class="change filter-first"></div>

It can normally be done with addClass and removeClass. But is there a way to do this with regex?

AlwaysStudent
  • 1,354
  • 18
  • 49

1 Answers1

1

No need for jQuery here.

const changeMe = document.getElementById('changeMe');

for (const listItem of document.querySelectorAll('.click')) {
  listItem.addEventListener('click', function() {
    changeMe.className = `change first-${listItem.id}`
  })
}
.click::before { content: attr(id); }

#changeMe::before { content: attr(class); }
<div class="change" id="changeMe"></div>
<hr>
<div class="list">
  <div class="click" id="first"></div>
  <div class="click" id="second"></div>
  <div class="click" id="third"></div>
</div>

If for whatever reason you insist on using jQuery:

const $changeMe = $('#changeMe');

$('.click').on('click', function() {
  $changeMe.attr('class', `change first-${this.id}`);
})
.click::before {
  content: attr(id);
}

#changeMe::before {
  content: attr(class);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="change" id="changeMe"></div>
<hr>
<div class="list">
  <div class="click" id="first"></div>
  <div class="click" id="second"></div>
  <div class="click" id="third"></div>
</div>
connexo
  • 53,704
  • 14
  • 91
  • 128