简体   繁体   中英

Remove of string from dom element id

I need to remove a string ("DTE_Field_") from the id of elements in the dom.

<select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select>

var str=$(el).attr("id");
str.replace("DTE_Field_","");

Use attr() method with callback . That will iterate over element and you can get old attribute value as callback argument you can update attribute by returning string where DTE_FIELD using String#replace method.

$('select').attr('id', function(i, oldId) {
  return oldId.replace('DTE_field_', '');
});

 $('select').attr('id', function(i, oldId) { return oldId.replace('DTE_Field_', ''); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select> 


If the element is not always select then you can use attribute contains selector (or if DTE_field_ is always at the beginning then use attribute starts with selector ).

$('[id*="DTE_field_"]').attr('id', function(i, oldId) {
  return oldId.replace('DTE_field_', '');
});

You can split the string( id ) and use pop() method to get the last element of the array

var str=$('#DTE_Field_CD_PAIS').attr("id");
alert(str.split("DTE_Field_").pop());

JSFIDDLE

Use like this:

var string=$('#DTE_Field_CD_PAIS').attr("id");
console.log(str.split("DTE_Field_").pop());
$('[id^="DTE_FIELD_"]').each(function () {
   $(this).attr('id', $(this).attr('id').replace('DTE_FIELD_',''));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM