Before moving on to the practical implementation, first, look at the sample tooltip whose value will extract using jQuery:
In the above code lines:
- The “<center>” tag adjusts the alignment of an element to the center of the web page:
- The “<label>” tag specifies the name of the added input field.
- The “<input>” tag adds an input element with the type “text”, id “myTooltip”, and the specified “title” attribute. The added tooltip with the specified value will appear on hovering the mouse over the associated element.
The above output pops up a tooltip by hovering the mouse over the given input field.
Now extract the created tooltip’s value using the “attr()” method.
Method 1: Extract Tooltip Values Using “attr()” Method
jQuery offers the “attr()” method that sets, modifies, and retrieves the attribute values of the specified HTML element. In this method, it is used to extract the tooltip value of the matched HTML element that is being set with the help of the “title” attribute.
The following code block shows its practical implementation:
$("document").ready(function(){
$("button").click(function(){
alert($("#myTooltip").attr("title"));
}) ;
});
</script>
In this code block:
- Firstly, the “ready()” method executes the specified functions when the current HTML document is loaded on the browser.
- Next, the “click()” method runs the given function when its associated “button” selector is clicked.
- An “alert box” is created that applies the “attr()” method to extract the “title” attribute value of the accessed HTML element and display it using the alert box.
Output
It can be seen that the given button pops up an alert box displaying the tooltip value of the input field.
Method 2: Extract Tooltip Values Using “prop()” Method
Another method to extract the “tooltip” values is jQuery’s “prop()” method. The “prop()” method sets, modifies, and returns the property values of the desired HTML element. For this scenario, it is utilized to get the values of the tooltip.
Here is its practical implementation:
$("document").ready(function(){
$("button").click(function(){
alert($("#myTooltip").prop("title"));
}) ;
});
</script>
Now, the “prop()” method is used to retrieve the tooltip value of the accessed HTML element.
Output
The output is identical to the “attr()” method.
That’s all about extracting the tooltip values using jQuery.
Conclusion
To extract the tooltip values, use the pre-defined “attr()” or the “prop()” method of jQuery. Both methods are easy to use and understand. They take the “title” attribute as their argument and return its value which is the tooltip value. Apart from this, these methods can also be used to extract the other attribute values of the selected HTML element. This post has practically explained all possible methods to extract tooltip values using jQuery.