Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery get content and attributes

jQuery - Get Content and Attributes


jQuery has powerful methods for manipulating HTML elements and attributes.


jQuery DOM manipulation

A very important part of jQuery is the ability to manipulate the DOM.

jQuery provides a range of DOM-related methods, making it easy to access and manipulate elements and attributes.

| lamp | DOM = Document Object Model

 

DOM 定义访问 HTML 和 XML 文档的标准:

"W3C 文档对象模型独立于平台和语言的界面,允许程序和脚本动态访问和更新文档的内容、结构以及样式。"

|

| --- | --- |


Get content - text(), html() and val()

Three simple and useful jQuery methods for DOM manipulation:

The following example shows how to get content with the jQuery text() and html() methods:

Example

$

(

"

#btn1

"

)

.

click

(

function

(

)

{

alert

(

"

Text:

"

(

"

#test

"

)

.

text

(

)

)

;

}

)

; $

(

"

#btn2

"

)

.

click

(

function

(

)

{

alert

(

"

HTML:

"

(

"

#test

"

)

.

html

(

)

)

;

}

)

;

Try it »

The following example shows how to get the value of an input field with the jQuery val() method:

Example

$

(

"

#btn1

"

)

.

click

(

function

(

)

{

alert

(

"

Value is:

"

(

"

#test

"

)

.

val

(

)

)

;

}

)

;

Try it »


Get attributes - attr()

The jQuery attr() method is used to get attribute values.

The following example shows how to get the value of the href attribute in a link:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

alert

(

$

(

"

#runoob

"

)

.

attr

(

"

href

"

)

)

;

}

)

;

Try it »

The next chapter explains how to set (change) content and attribute values.