2011-04-07 27 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);});