2011-04-07 26 views
1

說我有這樣的HTML代碼:jQuery的獲取屬性和元素的值

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

我可以通過它的id引用元素:$('#idgoeshere'))現在,我想該元素的所有屬性和它們的值:

src=srcgoeshere 
otherproperty=value 

有沒有什麼辦法可以通過編程方式使用jQuery和/或純Javascript?

+0

請注意,一個元素的屬性與元素的屬性不同。 – Flimm 2015-06-12 09:15:25

回答

5

您可以通過檢查屬性屬性得到的列表:

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

語法

$( 'idgoeshere')ATTR( 'otherproperty')

欲瞭解更多信息 - http://api.jquery.com/attr/

+0

我想他想列出所有的屬性,而不是一些具體的屬性。 – 2011-04-07 15:37:03

0

是的,你可以!

的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'); 
+0

您還可以設置屬性: – 2011-04-07 15:37:09

+0

$('#idgoeshere')。attr('src','myimage.jpg'); – 2011-04-07 15:37:39

0

您可以使用該attr

對於如。

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

試試這個:

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