Можно ли как то в js поменять путь svg картинки в html?
<svg class="svgColorTheme"><use xlink:href="image/svg/all.svg#MoonTheme"></use></svg>
Ответы (2 шт):
Автор решения: De.Minov
→ Ссылка
Используйте для этого .setAttributeNS()
document.querySelector('.svgColorTheme use').setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'image/svg/all.svg#SunTheme');
Автор решения: Qwertiy
→ Ссылка
Можно поменять с помощью setAttribute или setAttributeNS:
document.addEventListener('click', e => {
var id = e.target.id
var use = document.querySelector('use')
if (id === 'blue') {
use.setAttribute('xlink:href', '#' + id)
} else if (id === 'red') {
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#' + id)
}
})
html, body { height: 100%; }
body { display: grid; margin: 0; }
svg { width: 100vmin; margin: auto; --cursor: pointer; }
circle { cursor: var(--cursor); }
use { --cursor: auto; }
<svg viewBox="0 -5 19 19">
<circle id="blue" cx="5" r="4" fill="blue" />
<circle id="red" cx="14" r="4" fill="red" />
<use xlink:href="#blue" y="9" />
</svg>