Syntax of .text() Method
To return content:
$(selector).text()
To set text content:
$(selector).text(content)
To set text content using a function:
$(selector).text(function (index, content)
Set and Get content of an element using text()
In this example, I am using the "text()" method to return the text content (only) of an element and at the same time setting or assigning the text content to another element.
Let us assume, I have a P element and I want the script to return the elements text content only. Look inside the P element and you will see that some part of the content is within the <strong> tag. The HTML code will be ignored by text() method.
<body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div> <p id='intro'>Hello, I am <strong>Arun Banik</strong></p> <input type='button' id='bt' value='Click it'> <span id='sp1'></span> </div> </body> <script> $(document).ready(function () { $('#bt').click(function () { $('#sp1').text($('#intro').text()); // get and set text content only. }); }); </script>
To get and set text content along with html code, simply change "text()" to "html()". For example,
$('#sp1').html($('#intro').html());