使用Javascript在HTML中提取标签的属性 [英] Extract property of a tag in HTML using Javascript

查看:91
本文介绍了使用Javascript在HTML中提取标签的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Javascript提取 HTML标记的属性。
例如,我想知道< div> 里面的值,它有 align =center

 < div align =center> Hello< / div> 

我知道的是:

  var division = document.querySelectorAll(div); 

,但它会选择< div> &安培; < / div> ,而不是属性里面。



我想在 Greasemonkey脚本中使用它,我可以使用 Javascript 来检查网站中一些恶意属性



希望我明白.. !!

解决方案

您正在寻找 getAttribute 功能。你可以像这样使用它。

 <$ c可以通过元素访问它。 

(var i = 0,length = division.length; i {
var element =除法[I];
var alignData = division.getAttribute('align'); // alignData = center
if(alignData ==='center')
{
console.log('Data Found!');




$ b $ p
$ b

如果你想查看哪些属性可用在元素上,这些可以通过

  division.attributes 

MDN属性



例如在你的例子中,如果你想查看一个对齐属性是否可用,你可以写这个。

  //测试元素
是否存在属性if(division.attributes.hasOwnProperty('align'))
{
//它的确如此!
}


Is it possible to extract properties of a HTML tag using Javascript. For example, I want to know the values present inside with the <div> which has align = "center".

<div align="center">Hello</div>

What I know is:

var division=document.querySelectorAll("div");

but it selects the elements between <div> & </div> and not the properties inside it.

I want to use this in the Greasemonkey script where I can check for some malicious properties of a tag in a website using Javascript.

Hope I'm clear..!!

解决方案

You are looking for the getAttribute function. Which is accessible though the element.

You would use it like this.

var division = document.querySelectorAll('div')
for(var i=0,length=division.length;i < length;i++)
{
    var element = division[i];
    var alignData = division.getAttribute('align'); //alignData = center
    if(alignData === 'center')
    {
       console.log('Data Found!');
    }      
}

If you're looking to see what attributes are available on the element, these are available though

division.attributes

MDN Attributes

So for instance in your example if you wanted to see if an align property was available you could write this.

//Test to see if attribute exists on element
if(division.attributes.hasOwnProperty('align'))   
{
    //It does!
}

这篇关于使用Javascript在HTML中提取标签的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆