How can I change the <p> tag data dynamically after a certain time delay using javascript?

I want to change only the contents of the <p> tag using javascript after a certain time delay. For instance,

 <p>messages</p> 

should change depending on no. new posts. Because the

 <p>messages(1)</p> <p>messages(2)</p> 
+6
source share
3 answers

Write <p> as:

 <p class="messages">messages</p> 

Your javascript:

 function updateMessages() { var ps = document.getElementsByClassName("messages"); for(var i = 0, len = ps.length; i < len; i++) { ps[i].innerHTML = "messages (" + messageCount + ")"; } } setTimeout(updateMessages, 1000); 

Where 1000 is the number of milliseconds to delay.

Or if you want to do this periodically every 15 seconds, you can use setInterval :

 setInterval(updateMessages, 15000); 

UPDATE:

I see your comment above:

new messages are retrieved from the database using a JSP function that checks the database for new messages

In this case, in my opinion, do you want to receive this message periodically, actually checking this URL? If you are already using the javascript framework, I suggest you look at their AJAX documentation.

+6
source
 $(document).ready({ function updatePara() { $('p').html('Content to set in para'); } }); setTimeout(updatePara, no.of milisecond to delay); 

jQuery makes dom manipulation very easy :) The above code changes the contents of the entire paragraph. Therefore, it is better to give the required name paragragh <p></p> for any call name, then filter the item to update with that name ie $('p.classname').html('your content') OR $('.classname').html('Your content')
jQuery AWESOME !!! :)

+2
source

You can use the setTimeout function:

 var delay = 1000; // 1 second setTimeout(function() { var pNodes = document.getElementsByTagName('p'); for (var i=0, length=pNodes.length; i < length; i++) { pNodes[i].innerHTML = pNodes[i].innerHTML+"("+ (i+1) +")"; } }, delay); 

getElementsByTagName used as an example only. The way you extract pNodes depends on the structure of your html code.

+1
source

Source: https://habr.com/ru/post/908773/


All Articles