aacrea aacrea - 2 months ago 23
Javascript Question

is there a way to modify an attribute of a DOM element directly with jquery?

Does anybody know a way to shorten this:

$('.el').attr('src', $('.el').attr('src').replace('/subpath1/', '/subpath2/'))


Do it with a callback function where you can get the old attribute value as the second argument.

$('.el').attr('src',function(i, oldSrc){
  return oldSrc.replace('/subpath1/', '/subpath2/');

With ES6 arrow function

$('.el').attr('src', (i, s) => s.replace('/subpath1/', '/subpath2/'))

You can reduce the code length using capturing group regex.

$('.el').attr('src', (i, s) => s.replace(/(\/subpath)1\//, '$12/'))