Is there a way to change the attribute of a DOM element directly using jquery?

Does anyone know a way to shorten this:

$('.el').attr('src', $('.el').attr('src').replace('/subpath1/', '/subpath2/'))
+4
source share
2 answers

Do this using the callback function, where you can get the value of the old attribute as the second argument.

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

With function ES6 arrow

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

You can reduce the length of the code using the regular expression of the capture group.

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

You can also save your element in var first like this:

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

This way you will not need to scan the DOM a second time.

+1
source

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


All Articles