How can I change the <p> tag data dynamically after a certain time delay using javascript?
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.
$(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 !!! :)
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.