How many ways to get data from html element by jQuery?
In jQuery, there are several ways to get data from an HTML element. Here are some common methods along with examples:
Using .text()
method: This method gets the combined text contents of each element in the set of matched elements, including their descendants.
<div id="example">This is some text.</div> var text = $('#example').text(); console.log(text); // Output: "This is some text."
Using .html()
method: This method gets the HTML contents of the first element in the set of matched elements.
<div id="example"><p>This is <strong>bold</strong> text.</p></div> var html = $('#example').html(); console.log(html); // Output: "<p>This is <strong>bold</strong> text.</p>"
Using .val()
method: This method gets the current value of the first element in the set of matched elements.
<input type="text" id="example" value="Hello"> var value = $('#example').val(); console.log(value); // Output: "Hello"
Using .attr()
method: This method gets the value of an attribute for the first element in the set of matched elements.
<img id="example" src="image.jpg" alt="Example Image"> var src = $('#example').attr('src'); console.log(src); // Output: "image.jpg"
Using .data()
method: This method allows you to store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
<div id="example" data-info="Some information"></div> var info = $('#example').data('info'); console.log(info); // Output: "Some information"