Reputation: 61
".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 ?
Upvotes: 6
Views: 25693
Reputation: 53198
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()
Upvotes: 15
Reputation: 1219
You cannot cause it is JQuery
In pure Javascript use this (examples):
document.querySelector("a").getAttribute("href");
document.getElementById("My_img").getAttribute("width");
Upvotes: 2