Papier Moustachio
Papier Moustachio

Reputation: 41

Vanilla JavaScript replace element

I've looked around and can't seem to find a solution to directly replacing an element with a HTML string using vanilla JavaScript (not jQuery).

I'm storing a bunch of svg's in a directory that's publicly accessible, and I want to be able to include them in my files via the image tag <img src="path/to/svgs/example.svg">. However, this comes with its drawbacks as they can't be coloured/styled when they're pulled in as an image (to my knowledgE).

I discovered this example jQuery Image to SVG but obviously this uses jQuery's replaceWith function. I'm trying to replicate the functionality but struggling with the aforementioned function. All examples I've found end up creating a parent div element, and appending the new HTML to that newly created element.

TL;DR: Can I directly replace an element (IMG to SVG) using vanilla JavaScript without creating parent nodes?

Upvotes: 0

Views: 3693

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101820

Assuming you have already loaded the SVG into a string (via XmlHttpRequest, fetch etc). Then you can parse it using the DOMParser.

var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingSVGSource, "image/svg+xml");

See: Parse SVG and add it to a svg element

Then you can replace the original <img> using something like the insertBefore/removeChild method that Senad suggests.

Upvotes: 0

Senad Meškin
Senad Meškin

Reputation: 13756

jQuery is also using JavaScript behind replaceWith method, so if you want to replace one element with another you need to do next steps:

  1. Create new element
  2. Add it after/before an element that needs to be replaced
  3. Then remove original element

e.g If we have HTML list

<ul>
        <li>before</li>
        <li id="my-element">My element</li>
        <li>after</li>
    </ul>

and we want to replace list item, with id "my-element", with the new element then we need to do next:

//get reference to element that we want to replace
var elementToReplace = document.getElementById('my-element');
//create new element which will replace existing element
var newLi = document.createElement('li');
//just setting html in it
newLi.innerHTML = 'Just added';
//getting parent element reference and executing method "insertBefore" passing our new element and reference of element that we want to replace
elementToReplace.parentNode.insertBefore(newLi, elementToReplace.nextSibling);
//then we remove original element
elementToReplace.parentNode.removeChild(elementToReplace);

I hope this helps.

Upvotes: 2

Related Questions