1

Say I have this HTML code:

    <img id="idgoeshere" src="srcgoeshere" otherproperty="value" />

I can reference the element by its id: $('#idgoeshere')) Now, I want to get all the properties and their values on that element:

src=srcgoeshere
otherproperty=value

Is there some way I can do that programmatically using jQuery and/or plain Javascript?

mareoraft
  • 3,474
  • 4
  • 26
  • 62
Entity
  • 7,972
  • 21
  • 79
  • 122
  • Please be aware that a property of an element is not the same thing as an attribute of an element. – Flimm Jun 12 '15 at 09:15

6 Answers6

5

You can get a listing by inspecting the attributes property:

var attributes = document.getElementById('idgoeshere').attributes;
// OR
var attributes = $('#idgoeshere')[0].attributes;
alert(attributes[0].name);
alert(attributes[0].value);

$(attributes).each(function()
{
    // Loop over each attribute
});
Tejs
  • 40,736
  • 10
  • 68
  • 86
2

The syntax is

$('idgoeshere').attr('otherproperty')

For more information - http://api.jquery.com/attr/

Tomas McGuinness
  • 7,651
  • 3
  • 28
  • 40
0

Try this:

var element = $("#idgoeshere");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
Aki143S
  • 809
  • 7
  • 5
0

Yes you can!

Jquery:

var src = $('#idgoeshere').attr('src');
var otherproperty = $('#idgoeshere').attr('otherproperty');

Javascript:

var src = document.getElementById('idgoeshere').getAttribute('src');
var otherproperty = document.getElementById('idgoeshere').getAttribute('otherproperty');
Daniel Node.js
  • 6,734
  • 9
  • 35
  • 57
0

You can use attr for that:

For eg.

var mySrc = $('#idgoeshere').attr("src");
var otherProp = $('#idgoeshere').attr("otherproperty");
Sang Suantak
  • 5,213
  • 1
  • 27
  • 46
0

If you want to just get a list of all the attributes, see the answers to this question: Get all Attributes from a HTML element with Javascript/jQuery

Community
  • 1
  • 1
jches
  • 4,542
  • 24
  • 36