-4
 <body onload="myfunction('target')"><div id="target"> "Hello World" </div></body>

Is It Possible To Put Another Div Or HTML Element Replacing "Hello World" Text? Hello World is a Left To Right Marquee Text

<script language="javascript">
  function myfunction(id) {
    var element = document.getElementById(id);
    var textnode = element.childNodes[0];
    var text = textnode.data;

    setInterval(function() {
      text = text[text.length - 1] + text.substring(0, text.length - 1);
      textnode.data = text;
    }, 400)
  }
</script>

4 Answers4

0

If you're just trying to replace the text that is in the innerHTML/innerText querying the HTML element and simply setting it's innerHTML/innerText to the new value will suffice.

Example: const myElement = document.getElementByTagName('h1') myElement[0].innerHTML = 'new value'

  • The code is already rewriting the text inside the element, (try the "run code snippet" in the question) – xec Aug 29 '18 at 07:45
0

if you want to change html inside div and change to another div or text or any html you can do like this you don't need to replace

$('#target').html('<div class="col-md-2"></div>');

and if you want to replace then you can do like this

$('#target').html().replace("hello",'<div class="col-md-2"></div>');
Ahmed Sunny
  • 2,160
  • 1
  • 21
  • 27
  • 1
    `.replace()` creates a new string, it will not write the new content to the element – xec Aug 29 '18 at 08:03
0

innerHTML should do the trick, if you are trying to add html elements:

Here is the working example of your code snippet:

https://codebrace.com/editor/b15cd15b3

Example:

...
element.innerHTML = "<span style='color: red; background-color:yellow;'>" + text + "</span>";
...
0

html code

<body onload="myfunction()">
  <div id="target"> Hello World </div>
</body>

javascript code

function myFunction() {
    var str = document.getElementById("target").innerHTML; 
    var res = str.replace("Hello World", "testing");
    document.getElementById("target").innerHTML = res;
}

myFunction();

Replacing the helloworld html to testing html using onload function.

vinoth s
  • 178
  • 6