Delete last character in id attribute

I am trying to remove the last character from an id div using jQuery. I currently have:

    <div id="foo/"></div>

But I need:

    <div id="foo"></div>

A character is always /and is generated automatically (re: annoyingly) using the CMS that I use. Having /, I'm trying to use some JavaScript links.

How to fix this problem?

+3
source share
4 answers

Easily using a attribute$=CSS3 selector that means "ends" in your jQuery selection:

$("div[id$=/]").each(function(){ 
    this.id = this.id.substr(0,this.id.length - 1);
});

: Adobe® Browser Lab, IE6, IE7, Firefox 2.0 Firefox 3.0, Safari 3.0. Safari 4.0 Firefox 3.5. / .

+13

div id , / , :

$('div[id]').each(function(){
    var id = $(this).attr('id');
    if (id.indexOf('/') == id.length-1) {
      $(this).attr('id', id.slice(0, -1));
      // or $(this).attr('id', id.substring(0, id.length-1));
    }
});
+4

to try:

$("div").each(function(){
    var i=$(this).attr("id");
    if(i){
         i = i.substr(0,i.length-1);
         $(this).attr("id",i);
    }
});
0
source

This can do it:

$('*').each(function(){
  $(this).attr('id', $(this).attr('id').replace(/\/$/, ''));
});

Replace *with divor any css selector supported by jquery.

0
source

Source: https://habr.com/ru/post/1723838/


All Articles