
Get in Jquery
In jQuery, the term "get" usually refers to retrieving elements, values, or data from the DOM (Document Object Model). jQuery provides several methods to get content, attributes, values, or elements.
Here’s a breakdown of the most common "get" methods in jQuery:
? 1. .get()
Method
Used to retrieve DOM elements from a jQuery object.
Syntax:
$(selector).var el = $("p").get(0); // Get the first <p> element as a raw DOM nodeconsole.log(el.innerHTML);
? 2. .text()
Method
Gets the combined text content of selected elements.
Syntax:
$(selector).text()
Example:
var txt = $("#demo").text();alert(txt);
<p var htmlContent = $("#demo").html();console.log(htmlContent);
<p <input var name = $("#name").val(); alert(name); // Output: John</script>
? 5. .attr()
Method
Gets the value of an attribute from the first matched element.
Syntax:
$(selector).<img var src = $("#img1").attr("src"); alert(src); // Output: cat.jpg</script>
? 6. .data()
Method
Gets data stored using jQuery’s .data()
method.
Example:
var id = $("#box").data("id"); var user = $("#box").data("user"); console.log(id, user); // Output: 123, admin</script>
? Summary Table
Method | Description |
---|---|
.get() | Gets DOM element(s) from jQuery object |
.text() | Gets text content |
.html() | Gets HTML content |
.val() | Gets value of form input |
.attr() | Gets attribute value |
.data() | Gets custom data attribute |
? Real-Life Example:
var name = $("#username").val(); // "Alice" var greeting = $("#info").text(); // "Welcome Alice" var htmlGreeting = $("#info").html(); // "Welcome <b>Alice</b>" var logoSrc = $("#logo").attr("src"); // "logo.png"</script>
Want to see how to set values instead? Or dive into .getJSON()
and .ajax()
for getting data from a server?