jQuery provides a variety of methods to get or set the content of elements. These methods allow you to manipulate both the text and HTML inside elements, as well as their attributes, making it easy to dynamically update the content of your web pages.
Get Methods
.html()
: Gets the HTML content of the selected element(s).var content = $("#myDiv").html(); alert(content); // Displays the HTML content of #myDiv
.text()
: Gets the text content of the selected element(s), excluding any HTML tags.var content = $("#myDiv").text(); alert(content); // Displays the text content of #myDiv
.val()
: Gets the value of form elements like<input>
,<textarea>
, and<select>
.var value = $("#myInput").val(); alert(value); // Displays the value of the input field #myInput
.attr()
: Gets the value of an attribute for the selected element.var src = $("#myImage").attr("src"); alert(src); // Displays the src attribute of #myImage
Set Methods
.html(content)
: Sets the HTML content of the selected element(s).$("#myDiv").html("<strong>New HTML content</strong>");
.text(content)
: Sets the text content of the selected element(s).$("#myDiv").text("New text content");
.val(value)
: Sets the value of form elements like<input>
,<textarea>
, and<select>
.$("#myInput").val("New value");
.attr(attributeName, value)
: Sets the value of an attribute for the selected element.$("#myImage").attr("src", "newImage.jpg");