Full width home advertisement

Post Page Advertisement [Top]

differencejQuery

Difference between text() and html() in jQuery

Difference between text() and html() in jQuery

What is the use of text() and html() in jQuery.


Hello, Learners, Hope you are doing well. Today I am gonna show you best difference between text() and html() in jQuery. Before the difference, we should know each of them individually so that we can easily differentiate between them. Let's see.

What is the use of text() in jQuery?


text() is used to set the text of selected HTML element. Simply, you can rewrite text between starting and ending HTML tag.

For example, 

We have <h1>Krazzy Codes</h1> and We want to set text 
Hello World between <h1>

</h1>. So simply write, 

<script type=text/javascript>   
jQuery(document).ready(function(){      
var get_h1_text = $(h1).text(Hello World);       
alert(get_h1_text);   
});
</script>

OUTPUT : <h1>Hello World</h1>


text() is also used to retrieve text between HTML tag.

For example, 
We have <h1>Krazzy Codes</h1> and We want to get text between <h1> 
</h1>.So simply write, 

<script type=text/javascript>   

jQuery(document).ready(function(){      
var get_h1_text = $(h1).text(); 
alert(get_h1_text);   
});
</script>

OUTPUT : Krazzy Codes


ADDITIONAL READING ON KRAZZYCODES
  1. Basics of GITHUB and GIT
  2. Getting an error after php artisan config:cache in Laravel
  3. How to run artisan command on the server?
  4. 15 hidden USSD codes that reveal iPhone secret details
  5. Active Directory implementation in PHP or Laravel


What is the use of html() in jQuery?

html() is used to get & set content between HTML tag including HTML elements. For example,

We have html like following, we want to retrieve whole P tag with text.
<div id=wrapper_div>    
<p>Hello, Krazzy Coders</p>
</div>

<script type=text/javascript>   
jQuery(document).ready(function(){      

var get_wrapper_html = $(div).html();
alert(get_wrapper_html);   
});</script>

OUTPUT : <p>Hello, Krazzy Coders</p>


html() is also used to set html into the specified jQuery selector.

We have html like following, we want to replace P tag with 
<p>Hello World</p>.
<div id=wrapper_div>    
<p>Hello, Krazzy Coders</p>
</div>

<script type=text/javascript>   
jQuery(document).ready(function(){        
$(div).html(<p>Hello World</p>);    
});
</script>

OUTPUT : 
                       <div id=wrapper_div>    
                            <p>Hello World</p>
                       </div>

Difference between text() and html()


  1. text() is used to set and retrieve text in between html element(html tag).
  2. html() is used to set and retrieve HTML content in specified selector.
  3. html() is much faster than text().


If you still facing issues, then let me know via comment.
Dont be too selfish please do like, comment or share it.
Thank you for reading this post.

No comments:

Post a Comment

Bottom Ad [Post Page]