Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I use ".attr()" function in javascript?

Tags:

javascript

".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 ?

like image 637
Muthulakshmi S Avatar asked Aug 28 '26 22:08

Muthulakshmi S


2 Answers

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()

like image 61
BenM Avatar answered Aug 30 '26 13:08

BenM


You cannot cause it is JQuery

In pure Javascript use this (examples):

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


document.getElementById("My_img").getAttribute("width");
like image 23
3pic Avatar answered Aug 30 '26 13:08

3pic