jQuery API - DOM Attributes (DOM 属性)

创建时间:
2018-04-29 16:09
最近更新:
2018-10-02 00:18

All about CSS methods moved to the CSS-file by Tony.

文档汇总

Category: Attributes - These methods get and set DOM attributes of elements.

  1. .addClass(): Adds the specified class(es) to each element in the set of matched elements.
  2. .attr(): Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
  3. .hasClass(): Determine whether any of the matched elements are assigned the given class.
  4. .html(): Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
  5. .prop(): Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.
  6. .removeAttr(): Remove an attribute from each element in the set of matched elements.
  7. .removeClass(): Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
  8. .removeProp(): Remove a property for the set of matched elements.
  9. .toggleClass(): Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.
  10. .val(): Get the current value of the first element in the set of matched elements or set the value of every matched element.

.attr()

Get

.attr(attributeName)
attributeName: The name of the attribute to get.
Returns: String
Description: Get the value of an attribute for the first element in the set of matched elements.

Tony 测试记录:
测试代码: $(Selector).attr(AttributeName);
测试结果:
Selector 无匹配时,attr() 任何 AttributeName 均返回 undefined
Selector 有匹配时,attr() 任何不存在的 AttributeName 均返回 undefined

Example:
Find the title attribute of the first "em" tag in the page:

$('em').attr('title');

Example:
返回文档中第一个图像的src属性值:

$('img').attr('src');

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

如果元素没有相应属性,则返回 undefined:
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Using jQuery's .attr() method to get the value of an element's attribute has two main benefits:
Convenience:
It can be called directly on a jQuery object and chained to other jQuery methods.
Cross-browser consistency:
The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

Set

Returns: jQuery
Description: Set one or more attributes for the set of matched elements.

.attr(attributeName,value)
attributeName: The name string of the attribute to set.
value: A value to set for the attribute.
为所有匹配的元素设置一个属性值。

Example:

//为所有图像设置 src 属性:
$('img').attr('src','test.jpg');

.attr(map)
map: A map of attribute-value pairs to set.
将一个 "名/值" 形式的对象设置为所有匹配元素的属性。
这是一种在所有匹配元素中批量设置很多属性的最佳方式。
注意,如果你要设置对象的 class 属性,你必须使用 className 作为属性名。或者你可以直接使用 .addClass(class).removeClass(class)

Example:

//为所有图像设置 src 和 alt 属性:
$('img').attr({
    src: 'test.jpg',
    alt: 'TestImage'
});

.attr(attributeName,function(index,oldAttributeValue))
attributeName: The name of the attribute to set.
function(index,oldAttributeValue): A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.
为所有匹配的元素设置一个计算的属性值。

Example:

$('img').attr('title', function(){
    return this.src;
});

The .attr() method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function.

$('#greatphoto').attr('alt', 'Beijing Brush Seller');
$('#greatphoto').attr('title', 'Photo by Kelly Clark');

Example:
Setting several attributes at once:
To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute:

$('#greatphoto').attr({
    alt:'Beijing Brush Seller',
    title:'photo by Kelly Clark'
});

When setting multiple attributes, the quotes around attribute names are optional.
WARNING: When setting the 'class' attribute, you must always use quotes!

Note: jQuery prohibits changing the type attribute on an input or button element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.

Computed attribute values:
By using a function to set attributes, you can compute the value based on other properties of the element. For example, to concatenate a new value with an existing value:

$('#greatphoto').attr('title', function(index, oldAttributeValue){
    return oldAttributeValue + ' - photo by Kelly Clark';
});

This use of a function to compute attribute values can be particularly useful when modifying the attributes of multiple elements at once.

Note: If nothing is returned in the setter function (ie. function(index, attr){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

Example:
Set some attributes for all img tags in the page:

$('img').attr({
    src: '/images/hat.gif',
    title: 'jQuery',
    alt: 'jQueryLogo'
});
$('div').text($('img').attr('alt'));

Example:
Set the id for divs based on the position in the page:

$('div')
.attr('id', function(index){
    return 'div-id' + index;
})
.each(function(){
    $('span',this).html('(ID="'+this.id+'")');
});

Example:
Set the src attribute from title attribute on the image:

$('img').attr('src', function(){
    return '/images/' + this.title;
});

.removeAttr(attributeName)

attributeName: An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.
Returns: jQuery
Description: Remove an attribute from each element in the set of matched elements.

The .removeAttr() method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers.

Note: Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 6, 7, or 8. To avoid potential problems, use .prop() instead:

$element.prop('onclick', null);

Example:
将文档中图像的src属性删除:

$('img').removeAttr('src');

.prop()

Get

.prop(propertyName)
propertyName: The name of the property to get.
Returns: String
Description: Get the value of a property for the first element in the set of matched elements.

有可能返回 undefined:
The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

Set

Description: Set one or more properties for the set of matched elements.
.prop(propertyName,value)
propertyName: The name of the property to set.
value: A value to set for the property.

.prop(map)
map: A map of property-value pairs to set.

.prop(propertyName,function(index,oldPropertyValue))
propertyName: The name of the property to set.
function(index,oldPropertyValue): A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.

Example:

$('input').prop('disabled',false);
$('input').prop('checked',true);
$('input[type='checkbox']').prop('checked',function(i,val){return !val;});
$('input[type='checkbox']').prop({disabled:true});

.removeProp(propertyName)

propertyName: The name of the property to set.
Returns: jQuery
Description: Remove a property for the set of matched elements.

The .removeProp() method removes properties set by the .prop() method.

With some built-in properties of a DOM element or window object, browsers may generate an error if an attempt is made to remove the property. jQuery first assigns the value undefined to the property and ignores any error the browser generates. In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties.

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

Additional Notes:
In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data().

Example:
Set a numeric property on a paragraph and then remove it:

var $para = $('p');
$para.prop('luggageCode', 1234);
$para.append('The secret luggage code is: ', String($para.prop('luggageCode')), '. ');
$para.removeProp('luggageCode');
$para.append('Now the secret luggage code is: ', String($para.prop('luggageCode')), '. ');

为什么 jquery1.6+ 增加了 .prop() 方法?
在某些浏览器中只要写成 disabledchecked 就可以了;
而另一些浏览器中要写成 disabled="disabled"checked="checked"

使用 .attr() 操作 Boolean-Attributes 返回值不标准:
checkbox 已被选中则 .attr('checked') 值为 checked
checkbox 未被选中则 .attr('checked') 值为 undefined

所以,从 1.6 开始,jq 提供新的方法 .prop() 来获取这些属性,
prop() 将统一返回标准属性 true/false。而且赋值的时候也是如此。
如此,我们便统一了所有操作,无论是从语法上还是语义上。

哪些属性应该用 attr 访问、
哪些属性应该用 prop 访问?

3个原则:
1、仅添加属性名而无需添加属性值,该属性就会生效,这一类属性应该使用 .prop()
2、属性值为 true/false,这一类属性应该使用 .prop()
3、其他属性使用 .attr()。

官方文档如下:

用 .prop() 的:

  1. async
  2. autofocus
  3. checked
  4. location(i.e.window.location)
  5. multiple
  6. readOnly
  7. selected

用 .attr() 的:

  1. accesskey
  2. align
  3. class
  4. contenteditable
  5. draggable
  6. href
  7. id
  8. label
  9. rel
  10. src
  11. tabindex
  12. title
  13. type
  14. width(if needed over.width())

Example:
以下2行作用相同:

$(':checkbox').get(0).checked = true;
$(':checkbox:first').prop('checked', true);

.html()

TonyRemark: 此函数是对 innerHTML 的包装。
The .html() method is not available in XML documents. 这个函数的所有重载,均不能用于 XML 文档。

Get

.html()
Returns: String
Description: Get the HTML contents of the first element in the set of matched elements. 取得第一个匹配元素的 HTML 内容。

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.

Example:
Click a paragraph to convert it from html to text:

$('p').click(function(){
    $(this).text($(this).html());
});

Set

Returns: jQuery
Description: Set the HTML contents of each element in the set of matched elements.

Tony 测试记录: 此 set 方法的参数可为 JqueryObject、HTML 片段、文本或两者的混合体。
注意: 按 W3C 之类的标准,设置 body.innerHTML 时,body 的直接子代必须是 block/script/ins/del 这 4 种。

2012-07-12 Tony 阅读 jQuery 1.7.1 源码,发现:
当参数为 string 类型时,先尝试将参数赋给 innerHTML,如抛出异常则执行 this.empty().append(JqueryObject)
当参数为 JqueryObject 时,执行 this.empty().append(JqueryObject)

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content (详见下面的测试记录).

This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

.html(htmlString)
htmlString: A string of HTML to set as the content of each matched element.

.html(function(index,oldHtml))
function(index,oldHtml): A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldHtml argument to reference the previous content. Within the function, this refers to the current element in the set.

相关测试记录

//本测试结论:
//$(document) 与 $(document.body) 不同。向前者添加 DOM 无效。切记只能使用后者。
//执行 .innerHTML = 'NewValue' 或 .html('NewValue') 后,再使用 document.getElementById (原 innerHTML 中某元素的 id) 将返回 null,这意味着原 innerHTML 中的一切已不在 DOM 中。特别的是: 被清除的内容中的元素,如在清除前已被 JqueryObject 引用,则保留最外层的元素,但这个被保留的元素的 innerHTML 同样被清除。
//2012-07-07 Tony 编写 CommerceSg/A/Product/EditOld.aspx 页面中 ProductIntroList 的鼠标 hover 显示 IbPanel 时,因上述 2 问题走了弯路。
$(function(){
    var p;
    var jP = $('<p id="Id">In paragraph.</p>');

    alert('1、已创建JqueryObject、未添加至DOM: ');

    p = Id('Id');
    alert(p ? 'In DOM.' : 'Not in DOM.');//Not in DOM.
    alert(jP.html());//In paragraph.

    $(document).append(jP);//不能使用document!

    alert('2、已添加至$(document): ');

    p = Id('Id');
    alert(p ? 'In DOM.' : 'Not in DOM.');//Not in DOM.
    alert(jP.html());//In paragraph.

    $(document.body).append(jP);//必须使用document.body!

    alert('3、已添加至$(document.body): ');

    p = Id('Id');
    alert(p ? 'In DOM.' : 'Not in DOM.');//In DOM.
    alert(jP.html());//In paragraph.

    document.body.innerHTML = 'Replaced';

    alert('4、已更新innerHTML: ');

    p = Id('Id');
    alert(p ? 'In DOM.' : 'Not in DOM.');//Not in DOM.
    alert(jP.html() === '');//true.
    alert(jP[0].nodeName);//P.

    alert('Test end.');
});

.text()

TonyRemark: 此函数是对 createTextNode 的包装。

Get

注意:
Tony 在 D:\CodeAccumulation\ZenCoding.htm 页面中,使用 .text() 去获取 pre 里的内容,结果在 IE9 中,丢失了换行符。不使用 .text 而改用 innerHTML 后问题得到解决。
以后有机会要了解一下 .text() 的内部实现,找出错误的根源。

Returns: String
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
取得所有匹配元素的内容。结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对 HTML 和 XML 文档都有效。

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

As of jQuery 1.4, the .text() method returns the value of text and CDATA nodes as well as element nodes.

Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.

Example:
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).

$(document.body).html('<p><b>Test</b> Paragraph.</p><p></p>');
$('head').first().append('<style type='text/css'>p{color:#00f}b{color:#f00}</style>');
var ps=$('p');
var text=ps.first().text();
ps.last().html(text);

Set

Returns: jQuery
Description: Set the content of each element in the set of matched elements to the specified text.
设置所有匹配元素的文本内容。
此方法将覆盖全部 innerHTML,包括原来所有的后代元素与文本。

.text(textString)

textString: A string of text to set as the content of each matched element.

.text(function(index,oldText))

function(index,oldText): A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

Example:

$('ul li').text(function(index){
    return 'item number'+(index+1);
});

Unlike the .html() method, .text() can be used in both XML and HTML documents.

.html() 类似,但将编码 HTML (将 <> 替换成相应的 HTML 实体):
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as < for <).

Example:
Consider the following HTML:

<div class="demo-container">
    <div class="demo-box">Demonstration Box</div>
    <ul>
        <li>list item 1</li>
        <li>list <strong>item</strong> 2</li>
    </ul>
</div>

Execute:

$('div.demo-container').text('<p>This is a test.</p>');

Will produce the following DOM output:

<div class="demo-container">
<p>This is a test.</p>
</div>

The .text() method cannot be used on input elements. For input field text, use the .val() method.

Example:

$('p').text('<b>Some</b> new text.');

.val()

Get

Tony测试记录:
optionvalue 属性时,select.valuejQuery('select').val() 均为选中的 optionvalue
optionvalue 属性时,select.valuestring.Empty; jQuery('select').val()select.options[select.selectedIndex].text
所以,使用 jQuery 更佳。

Returns: String, Number, Array
Description: Get the current value of the first element in the set of matched elements.

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:

$('select.foo option:selected').val();//get the value from a dropdown select
$('select.foo').val();//get the value from a dropdown select even easier
$('input:checkbox:checked').val();//get the value from a checked checkbox
$('input:radio[name=bar]:checked').val();//get the value from a set of radio buttons

Note:
At present, using .val() on textarea elements strips carriage return characters from the browser-reported value.
When this value is sent to the server via XHR however,
carriage returns are preserved (or added by browsers which do not include them in the raw value).
A workaround for this issue can be achieved using a valHook as follows:

$.valHooks.textarea={
    get:function(elem){
        return elem.value.replace(/\r?\n/g,'\r\n');
    }
};

Example:

$('input').val();
$('#single').val();
$('#multiple').val().join(', ');
var multipleValues=$('#multiple').val()||[];multipleValues.join(', '));

Set

Returns: jQuery
Description: Set the value of each element in the set of matched elements.

.val(value)
value: A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.

Sample:

$('input').val('hello world!');
$('#single').val('Single2');

Sample:
value为StringArray时可为check,select,radio等赋值。

$('#multiple').val(['Multiple2','Multiple3']);
$('input').val(['check1','check2','radio1']);

.val(function(index,oldValue))
function(index,oldValue): A function returning the value to set. this is the current element. Receives the index position of the element in the set and the oldValue as arguments.

Sample:

$('input:text.items').val(function(){return this.value+''+this.className;});

attr() versus prop()

测试记录

var emptyOpt = jRef.find('[value=""]').prop('outerHTML');
//上一行有效、下一行无效,因为 attr() 是获取 HTML 上的 attribute; 而 prop() 是获取 DOM 上的 property。
var emptyOpt = jRef.find('[value=""]').attr('outerHTML');

Resource

  1. Category: General Attributes - .attr(), .prop(), .removeAttr(), .removeProp(), .val(): These methods get and set DOM attributes of elements
  2. jQuery 的 attr()prop() 的区别 - 对于检索和改变 DOM 的 properties,如表单元素的 checked、selected 或 disabled 状态,应使用 .prop() 方法。
  3. http://api.jquery.com/prop/
  4. http://www.jquery123.com/prop/
  5. http://api.jquery.com/attr/
  6. http://www.jquery123.com/attr/

html() 仅子元素、prop('outerHTML') 包含自身

jObj.html() 只能 get/set 子元素,不包含自身。
jObj.prop('outerHTML') 能够 get 自身。
jObj.prop('outerHTML', '<input>') 能够 set 自身。

removeAttr() 生产代码

//in "CodeGen\trunk\Site\Views\PropCol\Edit.cshtml":
jIdOfPropCol_Parent.removeAttr('data-val-required');

Resource

  1. jQuery 的 removeProp() 与 removeAttr() 移除属性的区别