Get Content-text (), HTML (), and Val ()
Three simple and practical jQuery methods for DOM manipulation:
- Text ()-Sets or returns the text content of the selected element
- HTML ()-Sets or returns the contents of the selected element (including HTML tags)
- Val ()-Sets or returns the value of a form field
Example
$ ("#btn1"). Click (function () { alert ("Text:" + $ ("#test"). Text ()); $ ("#btn2"). Click (function () { alert ("HTML:" + $ ("#test"). html ());});
Get Property-attr ()
The JQuery attr () method is used to get the property value.
The following example shows how to get the value of the href attribute in the link:
Example
$ ("button"). Click (function () { alert ("#www"). attr ("href");});
Set Content-text (), HTML (), and Val ()
Setting content:
- Text ()-Sets or returns the text content of the selected element
- HTML ()-Sets or returns the contents of the selected element (including HTML tags)
- Val ()-Sets or returns the value of a form field
Example
$ ("#btn1"). Click (function () { $ ("#test1"). Text ("Hello world!");}); $ ("#btn2"). Click (function () { $ ("#test2"). HTML ("<b>hello world!</b>");}); $ ("#btn3"). Click (function () { $ ("#test3"). Val ("Dolly Duck");});
The callback function for text (), HTML (), and Val ()
The three jQuery methods above: Text (), HTML (), and Val () also have a callback function. The callback function consists of two parameters: the subscript of the current element in the selected element list, and the original (old) value. Then return the string you want to use with the new value of the function.
Example
$ ("#btn1"). Click (function () { $ ("#test1"). Text (function (i,origtext) { return "old text:" + origtext + "New text : Hello world! (Index: "+ i +") "; }";}); $ ("#btn2"). Click (function () { $ ("#test2"). HTML (function (i,origtext) { return "old HTML:" + Origtext + "New Html:hello <b>world!</b> (index: "+ i +") "; }";});
JQuery-Get content and properties