1

Im trying to change every childNode in certain div to input using js like this:

<div class="change">
    sample text
    <h3>another one</h3>
    text
    <p>text</p>
</div>

->

<div class="change">
   <input type=text value='sample text'/> 
   <h3><input type=text value='another one'/></h3>
   <input type=text value='text'/>
   <p><input type=text value='text'/></p>
</div>

The sad thing is, that:

  • document.getElementsByClassName("change")[x].children[y]

    returns only the h3 and p. It can't return plaintext inside a div.

  • document.getElementsByClassName("change")[x].childNodes[o]

    is return-only. Still, if i would like to load everything into some var render and then do something like .innerHTML = render, it returns for every node something like [object HTMLHeadingElement]...

So I think that to do what I want to do, Im gonna need HTML for each Node, but I have no idea how to do this.

2 Answers2

0

You can just get the actual innerHTML value, and split on the new line to get each value:

var html = document.getElementsByClassName("change")[0].innerHTML;
var lines = html.split('\n');
var replace = '';

for(var i=0; i < lines.length; i++){
  var str = lines[i].trim();
  if(str == '') continue;
  replace += '<input type=text value="' +str+ '" />';
}

document.getElementsByClassName("change")[0].innerHTML = replace;

Also, I added trim in there to remove any extraneous lines from empty items.

koosa
  • 2,966
  • 3
  • 31
  • 46
  • Thanks! But - what if the element would take more than one line? like paragraph. also - and that is my bad (I had it wrong in my example), that I would like to have the tags like

    outside the input.

    – user3357655 Nov 28 '15 at 19:55
0

Use ID instead of class, I have updated your code below

<div id="change">
    sample text
    <h3>another one</h3>
    text
    <p>text</p>
</div>

->

<div class="change">
   <input type=text value='sample text'/> 
   <input type=text value='<h3>another one</h3>'/>
   <input type=text value='text'/>
   <input type=text value='<p>text</p>'/>
</div>

-> 

<script type="text/javascript">
    var el = document.getElementById("change");
    var child = el.firstChild;

    while (child) {
      if(child.nodeType == 3)
          console.log(child.nodeType  + child.nodeValue); // Here you can pick every Text element to do anything
      else
            console.log(child.nodeType  + child.innerHTML); // Here you can pick every child and do anything

        child = child.nextSibling;
    }
</script>
Furqan Aziz
  • 1,094
  • 9
  • 18