JQuery has a powerful way to manipulate HTML elements and attributes.
JQuery DOM Operations
A very important part of JQuery is the ability to manipulate the DOM.
JQuery provides a series of DOM-related methods that make it easy to access and manipulate elements and attributes.
Tip: DOM = Document Object model
The DOM defines the criteria for accessing HTML and XML documents:
The Document Object model is platform-and language-independent, allowing programs and scripts to dynamically access and update the content, structure, and style of the document. ”
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
The following example shows how to get the content using the JQuery text () and HTML () methods:
Instance
<! DOCTYPE html>$ (document). Ready (function() { $ ("#btn1"). Click (function( { alert ("Text:" + $ ("#test"). text ()); }); $ ("#btn2"). Click (function() { alert ("HTML:" + $ ("#test"). HTML ()); } ); </script>
View results:
The following example shows how to get the value of an input field using the JQuery Val () method:
Instance<! DOCTYPE html>$ (document). Ready (function() { $ ("button"). Click (function () { alert ("Value:" + $ ("#test"). Val ()); } ); </script>
View results:
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:
Instance<! DOCTYPE html>$ (document). Ready (function() { $ ("button"). Click (function () { alert ($ ("#w3s"). attr ("href")); } ); </script>
View results:JQuery-Get content and properties