用js获取网页DOM(例:input标签的ID)的chrome插件

本文介绍JavaScript中获取DOM元素的基本方法,包括getElementById等,并通过示例代码展示如何获取网页中的input标签ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[html]  view plain  copy
  1. </pre><p>在JavaScript中有多钟获取DOM元素的方法,常见的有getElementById、getElementsByName、getElementsByTagName、getElementsByClassName,分别是通过id、name、标签名和类名获取元素,注意只有第一个是Element,其他三个都是Elements,因为HTML中元素名必须唯一,其他则不必。下面就以获取网页input标签的ID为例:</p><p>1、</p><p>manifest.json:</p><p></p><pre name="code" class="html">{  
  2.     "manifest_version":2,  
  3.     "version":"1.0",  
  4.     "name":"getid",  
  5.     "description":"get elements'id",  
  6.     "icons":{  
  7.         "16":"images/icon16.png"  
  8.     },  
  9.     "content_scripts":[  
  10.         {  
  11.          "matches":["*://*/*"],  
  12.          "js":["js/content.js"]  
  13.          }  
  14.     ]  
  15. }  

conten.js:

[html]  view plain  copy
  1. window.onload = function(){  
  2.     var list=document.getElementsByTagName("input");  
  3.     var strData;  
  4.     for(var i=0;i<list.length && list[i];i++)  
  5.     {  
  6.         if(list[i].type == "text"&&list[i].id != "subEmail")  
  7.         {  
  8.             strData=list[i];  
  9.             alert(strData.id);  
  10.         }  
  11.     }  
  12. }  

加载插件成功后,重新载入页面,即可看到弹框显示的每个input的ID。

2、要是想通过页面间的通信来实现上面的功能:函数如下:

manifest.json:

[plain]  view plain  copy
  1. {  
  2.     "manifest_version":2,  
  3.     "version":"1.0",  
  4.     "name":"getid",  
  5.     "description":"get elements'id",  
  6.     "icons":{  
  7.         "16":"images/icon16.png"  
  8.     },  
  9.     "background":{  
  10.         "scripts":[  
  11.            "js/background.js"  
  12.         ]  
  13.     },  
  14.     "content_scripts":[  
  15.         {  
  16.          "matches":["*://*/*"],  
  17.          "js":["js/content.js"]  
  18.          }  
  19.     ]  
  20. }  

background.js:

[javascript]  view plain  copy
  1. /** 
  2.  * Created by Administrator on 15-1-4. 
  3.  */  
  4. chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){  
  5.     alert("ID都有"+message);  
  6.     });  

content.js:

[javascript]  view plain  copy
  1. /** 
  2.  * Created by Administrator on 15-1-4. 
  3.  */  
  4. window.onload = function(){  
  5.     var list=document.getElementsByTagName("input");  
  6.     var strData;  
  7.     for(var i=0;i<list.length && list[i];i++)  
  8.     {  
  9.         if(list[i].type == "text"&&list[i].id != "subEmail")  
  10.         {  
  11.             strData=list[i];  
  12.             chrome.runtime.sendMessage(strData.id);  
  13.         }  
  14.     }  
  15.   
  16. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值