text() method: Get only Text Content (excludes tags) of an HTML element in Jquery

Date Published: 11/05/2020Published By: JaiSchool

This method returns you text content of an element.

In Javascript, You use textContent property to get text content.

Get text content

<!DOCTYPE html>
<html>
<head>
  <title>Jquery text()</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>


<div id="main" style="border:2px solid black;width:400;height:200;">
  <h1>What is the full form of HTML?</h1>
  <p>The full form of the HTML is hyper text markup language.</p>
</div>


<button style="margin:30px;">Get text content</button>

<script>

$(document).ready(function(){
  $("button").click(function(){
    var textcontent = $("#main").text();
    alert(textcontent);
  });
});
</script>

</body>
</html>

If you want html content then you can use html() method in jquery.

Set text content

<!DOCTYPE html>
<html>
<head>
  <title>Jquery text()</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>


<div id="main" style="border:2px solid black;width:400px;height:200px;">
 
</div>


<button style="margin:30px;">Set text content</button>

<script>

$(document).ready(function(){
  $("button").click(function(){
    $("#main").text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.");
  });
});
</script>

</body>
</html>

Publish A Comment

Leave a Reply

Your email address will not be published.