Ali Babae
Ali Babae

Reputation: 169

How to change id attribute with jquery

How can I change the id attribute value from / to something like: -? Here is what is have:

<div id="Over/Under">

I tried to do this with JQuery:

$('[id^="Over/Under"]').each(function(){
  this.id = this.id.replace('Over/Under', 'over-under');  // Replace Id
});

However it's not working. Note that I don't have direct access to the id value

Upvotes: 0

Views: 192

Answers (1)

Martin
Martin

Reputation: 16423

If I understand you correctly, you want to change the id attribute of any tag with a forward-slash (/) to a hyphen (-).

You can easily achieve that using a id*= selector:

$('[id*="/"]').each(function(){
    console.log('ID before: ' + $(this).attr('id'));
    $(this).attr('id', $(this).attr('id').replace('/', '-'));
    console.log('ID after: ' + $(this).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="user/name">

This will find all elements with an id containing a forward-slash, and replace the id with a hyphenated one instead.

Console output:

ID before: user/name
ID after: user-name

Upvotes: 1

Related Questions