Entity
Entity

Reputation: 8222

jQuery get attributes and values of element

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?

Upvotes: 1

Views: 12231

Answers (6)

Aki143S
Aki143S

Reputation: 819

Try this:

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

Upvotes: 0

jches
jches

Reputation: 4527

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

Upvotes: 0

Sang Suantak
Sang Suantak

Reputation: 5265

You can use attr for that:

For eg.

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

Upvotes: 0

Daniel
Daniel

Reputation: 6842

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');

Upvotes: 0

Tejs
Tejs

Reputation: 41266

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
});

Upvotes: 5

Tomas McGuinness
Tomas McGuinness

Reputation: 7679

The syntax is

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

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

Upvotes: 2

Related Questions