如何操作DOM元素,并在chrome扩展脚本中替换它?

时间:2018-07-04 10:09:30

标签: javascript google-chrome-extension content-script

在chrome扩展程序中,如何处理原始html内容

  

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
  

必需的输出(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>

2 个答案:

答案 0 :(得分:0)

尝试这个简单的jquery代码。

var c = 2;
$(".demo .number").each(function(){
    $(this).html(c);
    c += 2;
});

答案 1 :(得分:0)

希望对您有帮助

  

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

} 
});

这将为您提供所需的输出,