javascript jQuery 获取元素的属性和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5583641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:40:56  来源:igfitidea点击:

jQuery get attributes and values of element

javascriptjqueryjquery-selectors

提问by Entity

Say I have this HTML code:

假设我有这个 HTML 代码:

    <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:

我可以通过它的 id 引用该元素:$('#idgoeshere'))现在,我想获取该元素上的所有属性及其值:

src=srcgoeshere
otherproperty=value

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

有什么方法可以使用 jQuery 和/或普通 Javascript 以编程方式做到这一点吗?

回答by Tejs

You can get a listing by inspecting the attributes property:

您可以通过检查 attributes 属性来获取列表:

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

回答by Tomas McGuinness

The syntax is

语法是

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

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

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

有关更多信息 - http://api.jquery.com/attr/

回答by Daniel says Reinstate Monica

Yes you can!

是的你可以!

Jquery:

查询:

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

Javascript:

Javascript:

var src = document.getElementById('idgoeshere').getAttribute('src');
var otherproperty = document.getElementById('idgoeshere').getAttribute('otherproperty');

回答by Sang Suantak

You can use attrfor that:

你可以使用attr

For eg.

例如。

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

回答by jches

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

如果您只想获取所有属性的列表,请参阅此问题的答案:Get all Attributes from a HTML element with Javascript/jQuery

回答by Aki143S

Try this:

试试这个:

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