简体   繁体   中英

Extract property of a tag in HTML using Javascript

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!
}
var test = document.querySelectorAll('div[align="center"]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM