Change icon structure in javascript

1

I'm starting development and I'm on a mission that's beating head and I do not know how to finish.

I need to change tag's <i> by <svg><use></svg> . This way I stop calling class and step by calling id , as shown below.

I would like to manipulate by js . Where <i class="ico-nomedoicone"> is in HTML, change to

<svg class="icon"><use xlink:href="icons/icons.svg#icon-nomedoicone"/></svg>

Could someone help me with a code idea?

I thought of something like this ...

var i = document.querySelectorAll("i");
        for(var i=0;i<=i.length;i++) {
            if(i[s].className == "ico-") { 
            i[i].innerHTML = "<svg class='icon'><use xlink:href='icons/icons.svg#icon-italic'/></svg>"; 
        }
    }
    
asked by anonymous 19.01.2018 / 18:23

2 answers

1

You can use the replaceWith method. .

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
    </head>

    <body>
        <span>Span (Not replaced)</span>
        <i>Italic (Not replaced)</i>
        <i class="icon-android">Icon (Replace)</i>
        <i class="icon">Icon (Not replaced)</i>
        <i class="icon-test">Second Icon (Replace)</i>

        <button type="button">Substituir icons</button>

        <script>
            const btn = document.querySelector("button");

            btn.addEventListener("click", () => {
                var elements = document.querySelectorAll("i[class*=icon-]");

                elements.forEach(element => {
                    let div = document.createElement("div");
                    div.innerHTML = "<svg class=\"icon\"><use xlink:href='android-icon.svg#android'/></svg>";

                    element.replaceWith( div.firstChild );
                })
            });
        </script>
    </body>
</html>

It is necessary for you to create a temporary element (with document.createElement ), in case you pass html "direct" JavaScript will consider string and write the code on the screen.

For demonstration follow the steps below:

  • Copy and paste the above code into a page .html
  • Download the image link
  • Add the downloaded image to the same directory where you created the .html above.
  • Access through your server.
  • 19.01.2018 / 18:31
    0

    Another way is to use createDocumentFragment() . In the example below I include a <circle> just for illustration, you should delete it.

    let els = document.querySelectorAll("i[class*='icon-']");
    let frag = document.createDocumentFragment();
    
    for(let item of els){
       let svg = '<svg class="icon"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /><use xlink:href="icons/icons.svg#'+item.classList+'" /></svg>';
       item.innerHTML = svg;
       frag.appendChild(item.removeChild(item.firstChild));
       item.parentNode.replaceChild(frag, item);
    }
    <i class="icon-nomedoicone">elemento 1</i>
    <i class="icon-italic">elemento 2</i>
        
    20.01.2018 / 00:40