herrfischer
herrfischer

Reputation: 1828

Replace special characters from IDs with jQuery

I have e. g. this code:

<article role="tabpanel" class="tab-pane" id="2.asdasdasdda">

and need to delete/replace the "." in the IDs.

I tried with:

$('.tab-pane').replace('.','LEAVE');

but nothing happens. What am I doing wrong here?

Upvotes: 0

Views: 31

Answers (3)

Jai
Jai

Reputation: 74738

You can use it this way:

$('.tab-pane').attr('id', function(){
   var id = this.id.replace('.','LEAVE');
   return id;
});

but nothing happens.

Surely! Your code won't work at you are trying to replace the . of the element's contents which is not the case.
Because you want to change an attribute id of it. So, .attr() method can be used with a function as a second parameter.

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You need to reassign the value of ID attribute.

$('.tab-pane').attr('id', function(_, value) {
  return value.replace('.', 'LEAVE');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article role="tabpanel" class="tab-pane" id="2.asdasdasdda">aaa</article>

Upvotes: 0

Roxoradev
Roxoradev

Reputation: 893

Try this (of course you can change "leave" with what you want):

console.log($(".tab-pane").attr("id"));
$(".tab-pane").attr("id",$('.tab-pane').attr("id").replace('.','LEAVE'));
console.log($(".tab-pane").attr("id"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<article role="tabpanel" class="tab-pane" id="2.asdasdasdda">

Upvotes: 0

Related Questions