-2
  • SCENARIO

I have the following HTML code snippet:

<div class="container">
    TEXT
    <p> PARAGRAPH 1 </p>
    <p> PARAGRAPH 2 </p>
    <p> PARAGRAPH 3 </p>
    <p> PARAGRAPH 4 </p>
</div>

I am required to change the plain text using JS/jQuery, using the HTML DOM methods.

  • PROBLEM

** I can access the "plain text" node using

document.getElementsByClassName("container")[0].childNodes[0]

** However, I can't use the innerHTML, as it returns "undefined":

document.getElementsByClassName("container")[0].childNodes[0].innerHTML

** Using the replaceChild method doesn't work either (it triggers an Uncaught DOMException at the console log).

    var textnode = document.createTextNode("THE TEXT HAS BEEN REPLACED");
    
    var element = document.getElementsByClassName("container")[0].childNodes[0];

    item.replaceChild(textnode, item);

** And finally, using

document.getElementsByClassName("container")[0].innerHTML

selects all the HTML content inside <div class="container">.

Is there any way I can access the text content of "TEXT" and change it dynamically?

  • JSFIDDLE

http://jsfiddle.net/kouk/4otbqc75/

Community
  • 1
  • 1
kouk
  • 81
  • 1
  • 6
  • I know it is bad practice displaying unformatted plain text like that, but I am required to handle this situation. If I could, I would simply add some HTML tags, however, I don't have a choice on this situation. – kouk Sep 29 '15 at 18:56
  • Use `textContent` instead of `innerHTML`. – Sebastian Simon Sep 29 '15 at 18:57
  • you can use regex for this. – Mohammadreza Yektamaram Sep 29 '15 at 18:57
  • 1
    Just a tip: stop using `alert()` for debugging. `console.dir()` would have given a strong hint about what property to change. – JJJ Sep 29 '15 at 18:57
  • Oh, I was directly debugging my code via the Chrome console; I should have also placed `console.dir`in my jsfiddle... thanks for the hint – kouk Sep 29 '15 at 19:10

2 Answers2

0

Simply like this

Demo

$(".container").html($(".container:first-child").html().replace("TEXT","TEXT CHANGED"));
Diptox
  • 1,809
  • 10
  • 19
0

It should be

document.getElementsByClassName("container")[0].childNodes[0].textContent = "New Text";
alepeino
  • 9,551
  • 3
  • 28
  • 48
  • 1
    `textContent` should not be used to `set`, but to `get` text, as it represents the text content of a node and all its descendants. In this example it works as the node `TEXT` has no children (but the rule still stands). – MaxZoom Sep 29 '15 at 19:41