27 Jan jQuery – Get Content
To get the content from a web page using jQuery, we can use the text(), html() and val() methods. In this lesson, we will learn how to,
- Get the Text of the selected element
- Get Content from the Form Fields
Get the Text of the selected element
To get the text of the selected element in jQuery, use the text() and html() methods. Let us see an example wherein we will get the text of the <p> element with id demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ alert($("#demo").text()); }); $("#btn2").click(function(){ alert($("#demo").html()); }); }); </script> <style> #demo { background: black; color: white; font-size: 22px; } button { background: red; color: white; font-size: 30px; text-align: center; padding: 15px; } </style> </head> <body> <h1>Demo Heading</h1> <p id="demo">This is a <em>demo text</em>. This is another <strong>demo text</strong>.</p> <p>Click the below button to get the text content or the HTML content of the above line.</p> <button id="btn1">Text</button> <button id="btn2">HTML</button> </body> </html> |
Output
Get Content from the Form Fields
To get the content from the Form fields, use the val() method in jQuery. Let us see another example wherein we will get the content from the form fields:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ alert($("#ename").val()); }); $("#btn2").click(function(){ alert($("#edept").val()); }); $("#btn3").click(function(){ alert($("#ezone").val()); }); }); </script> <style> button { background: red; color: white; font-size: 15px; text-align: center; padding: 15px; } </style> </head> <body> <h1>Employee Details</h1> <p>Employee Name: <input type="text" id="ename" value="Amit Thinks"/></p> <p>Employee Department: <input type="text" id="edept" value="Tech"/></p> <p>Employee Zone: <input type="text" id="ezone" value="North"/></p> <button id="btn1">Get the Employee Name</button> <button id="btn2">Get the Employee Department</button> <button id="btn3">Get the Employee Zone</button> </body> </html> |
Output
No Comments