aacrea aacrea - 1 year ago 71
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/'))

Answer Source

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/'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download