Search code examples
javascriptgoogle-chrome-extensioncontent-script

How to manipulate DOM elements,and replace it in chrome extension script?


In chrome extension,how to manipulate original html content

index.html

  <div class='demo'>
    <SPAN class ="number">1</SPAN>
<SPAN class ="number">2</SPAN>
<SPAN class ="number">3</SPAN>
<SPAN class ="number">4</SPAN>
    </div>

content.js

//some logic to get arrays of text in "number" class from html,then multiply with 2 , then update the index.html

required output (index.html)

  <div class='demo'>
    <SPAN class ="number">2</SPAN>
<SPAN class ="number">4</SPAN>
<SPAN class ="number">6</SPAN>
<SPAN class ="number">8</SPAN>
    </div>

Solution

  • hope this help you

    index.html

     <div class='demo'>
    <span  class ="number">1</span>
    <span  class ="number">2</span>
    <span  class ="number">3</span>
    <span  class ="number">4</span>
        </div>
        <button>d</button>
    

    content.js

    $("button").click(function(){
    
        x=document.getElementsByClassName("number");  // Find the elements
    for(var i = 0; i < x.length; i++){
    var y = parseInt(x[i].innerText) * 2;
    x[i].innerText= y;    // Change the content
    
    } 
    });
    

    This will give you desired output,