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

Before moving further, we’ve prepared a video tutorial to get content from a web page using jQuery:

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:

<!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 the Text of the selected element jQuery

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:

<!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

Get content from form fields jQuery

jQuery - Find Siblings of an element
jQuery - Set Content
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment