jQuery Get Text Examples – Get Anchor Text Hyperlink Text & more
Many times when working with different elements of a web page, we might feel the need to get it’s text. In this article, I am going to share a very easy way to get text of an anchor, a hyperlink or any other element using just 1 line code. Examples also follow, so read on.
Examples to Get Text of Anchor, Hyperlink, Select Dropdown, etc.
Let’s assume that we have few elements, such as anchor/hyperlinks, labels, etc. on a web page. We would like to get the text of these elements. So let’s start with the basic syntax first and then we will see some specific examples.
Basic Syntax to get the text of any element
$(element).text();
Example 1: Get Anchor Text / Get Hyperlink Text
Here is our anchor/hyperlink’s html code:
<a href="#" class="my_link">This is my link</a>
To get hyperlink text, simply use the following code:
alert( $('.my_link').text() );Example 2: Get Text of Label
Here is our label’s html code:
<label for="fname" id="label_fname">First Name</label> <input type="text" name="fname" id="fname">
To get label text , simply use the following code:
alert( $('#label_fname').text() );Example 3: Get Text of Selected Option of a Dropdown
Here is our Dropdown’s html code:
<select name="country" id="country"> <option value="Australia">Australia</option> <option value="London" selected="selected">London</option> <option value="USA">USA</option> </select>
To get selected option text of the dropdown, simply use the following code:
alert( $('#country option:selected').text() );To get the text of a specific option of the dropdown:
Here, we would like to get the text of the third option regardless of whether it is selected or not.
alert( $('#country option:eq(2)').text() );In the above code, note that we want to get the text of the 3rd option, so we have to use eq(2) & NOT eq(3) as indexing starts at 0. So if you want to get the text of the first option, then you would use:
alert( $('#country option:eq(0)').text() );To get the text of an option of the dropdown, based on its value:
Let’s assume that you want to get the text of the ‘USA’ option. It can be done like so:
alert( $('#country option[value="USA"]').text() );That’s it for now!
Do you know of any other ways to get anchor text / hyperlink text or text of any element using jQuery? Feel free to suggest by commenting below.