0

I want to have a text and right of it to have a image (arrow up or down). I used this code:

<div id="more-time1" class="small-text-size ">more time<span id="arr-icon" class="accordion_down"></span></div>

The external div holds the text and the internal span has the image (the image is data in the class). When I change the text of the div:

var moreTime = document.getElementById("more-time1");
moreTime.innerHTML = "less time";

It delete span and I can't change the image in it unless I add every time a new span to it.

My question is: Do I need to add span every time or I can have a better design which change text won't affect the span? Or maybe other solution?

Alex
  • 8,461
  • 6
  • 37
  • 49
Dror
  • 177
  • 3
  • 11

3 Answers3

1

When you set .innerHTML of the div, you are writing its entire contents. This means you are overwriting the image span.

Put your text into a span so you can target the text separately from the image within the div.

<div id="more-time1" class="small-text-size ">
    <span class="more-time1-text">more time</span>
    <span id="arr-icon" class="accordion_down"></span>
</div>

var moreTime = document.getElementById("more-time1-text");
moreTime.innerHTML = "less time";
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
1

You should surround your text inside an additional tag and then manipulate that.

HTML:

<div id="more-time1" class="small-text-size ">
   <span id="my-text">more time</span>
   <span id="arr-icon" class="accordion_down"></span>
</div>

JS:

   var moreTime = document.getElementById("my-text");
   moreTime.innerHTML = "less time";
Amr Noman
  • 2,597
  • 13
  • 24
0

Use code below to rich desired result:

var moreTime = document.getElementById("more-time1");
moreTime.childNodes[0].nodeValue = "Desired text"

Explaining: In code snippet above you accessing first child node of more-time1 element (which is textNode) and modifying value of that node.

Update: According to comment below to change text within your element you could start for loop over childNodes:

for (var latestTextNode, i=0; i < moreTime.childNodes.length; i++){
  if (moreTime.childNodes[i].nodeType == 3) {
    moreTime.childNodes[i].nodeValue = '';
    // keep link to latest text node to alter text later
    latestTextNode = moreTime.childNodes[i]; 
  }
};
latestTextNode && latestTextNode.nodeValue = 'Desired text';
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82