jQuery provides a set of methods to get content and attributes from HTML elements.
- Get Content:
a) .text(): returns the combined text contents of each element in the set of matched elements, including their descendants.
Example:
<p>This is a paragraph <span>with a span inside</span>.</p>
<script>
var textContent = $('p').text();
console.log(textContent); // Output: "This is a paragraph with a span inside."
</script>
b) .html(): returns the HTML contents of the first element in the set of matched elements or sets the HTML contents of each element in the set of matched elements.
Example:
<div id="myDiv">
<p>This is a paragraph.</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</div>
<script>
var htmlContent = $('#myDiv').html();
console.log(htmlContent); // Output: "<p>This is a paragraph.</p><ul><li>List item 1</li><li>List item 2</li></ul>"
</script>
- Get Attributes:
a) .attr(): gets the value of an attribute for the first element in the set of matched elements or sets one or more attributes for every matched element.
Example:
<a href="https://www.example.com" target="_blank">Click me</a>
<script>
var hrefValue = $('a').attr('href');
console.log(hrefValue); // Output: "https://www.example.com"
$('a').attr('target', '_self');
// The link will now open in the same window/tab
</script>
b) .data(): gets the value of a data attribute for the first element in the set of matched elements or sets data attribute values for every matched element.
Example:
<div id="myDiv" data-color="blue"></div>
<script>
var dataValue = $('#myDiv').data('color');
console.log(dataValue); // Output: "blue"
$('#myDiv').data('color', 'red');
// The data-color attribute will now have a value of "red"
</script>
