Extract property of a tag in HTML using Javascript

主宰稳场 提交于 2019-12-12 02:17:29

问题


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..!!


回答1:


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!
}



回答2:


var test = document.querySelectorAll('div[align="center"]');


来源:https://stackoverflow.com/questions/22800104/extract-property-of-a-tag-in-html-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!