6

".getAttribute" is used in java script inject coding. in java script function ".attr()" is used. So can I use ".attr" value is used in java script injection coding ?

Muthulakshmi S
  • 61
  • 1
  • 1
  • 2

2 Answers2

13

No. attr() is a function of jQuery (and some other Javascript libraries). It's not a native function of Javascript.

In jQuery, attr() should be called on a jQuery object or collection. It cannot be called against DOM Elements. As you have correctly identified, if you don't want to use a library, you'll need to use getAttribute().

The following examples show how to get the same information using both jQuery and Javascript:

Javascript:

var src = document.getElementById('myImg').getAttribute('src');

jQuery:

var src = $('#myImg').attr('src');

It also worth noting the difference in jQuery between attr() and prop(), for example:

attr( attribute )
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

prop( propertyName )
Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

You can read more about the differences here > .prop() vs .attr()

Community
  • 1
  • 1
BenM
  • 52,573
  • 26
  • 113
  • 168
2

You cannot cause it is JQuery

In pure Javascript use this (examples):

document.querySelector("a").getAttribute("href");


document.getElementById("My_img").getAttribute("width");
3pic
  • 1,188
  • 8
  • 26