Advertisement
lalatino

change text with javascript

Jul 19th, 2012
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Untitled Document</title>
  5. <style>
  6. #container {width:100%; text-align:center; }
  7. #heading {width:100%; text-align:center; }
  8. </style>
  9.  
  10. <script type="text/javascript">
  11. // simple way:
  12. function replace_text(text) {
  13.     var heading = document.getElementById('heading');
  14.     heading.innerHTML = '<h1>' + text + '</h1>';
  15. }
  16.  
  17. // complicated way:
  18. function replace_text2(text) {
  19.     var heading = document.getElementById('heading');
  20.     var node = heading.childNodes[0];
  21.     while ( node && node.nodeType!=1 && node.tagName!='H1' ){
  22.         //console.log(node.nodeType,node);
  23.         node = node.nextSibling;
  24.     }
  25.     if (node) {
  26.         node.replaceChild(document.createTextNode(text),node.childNodes[0]);
  27.     }
  28. }
  29.  
  30. </script>
  31.  
  32. </head>
  33.  
  34. <div id="heading">
  35. <h1>hello</h1>
  36. </div>
  37. <body>
  38. <div id="container">
  39. <textarea name="mytextarea" cols="60" rows="10">HELLO</textarea>
  40. </div>
  41.  
  42. <input type="button" onclick="replace_text(document.getElementsByName('mytextarea')[0].value);" value="Update header 1" />
  43. <input type="button" onclick="replace_text2(document.getElementsByName('mytextarea')[0].value);" value="Update header 2" />
  44. <input type="button" onclick="replace_text('Hello! 3');" value="Update header 3" />
  45. <input type="button" onclick="replace_text2('Hello! 4');" value="Update header 4" />
  46.  
  47. </body>
  48. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement