0
  <td  id="gender3" name ="gender">Male
      <input id = "gender_input3" type="text" style="border:ridge;width:90px; display: none" name="gender" >      
  </td>  

A td contains text and another dom called input. When certain action is triggered, I only want to clear the text.

td  = document.getElementById("gender3")
td.innerText = ""

This will also eliminate input tag.

How can I do? Thanks.

Alston
  • 2,085
  • 5
  • 30
  • 49
  • Bind that action to event listener, and whenever that even is triggered, you can clear the text. Something like https://stackoverflow.com/questions/20586072/javascript-bind-an-objects-method-to-event-handler – Raja G Nov 10 '22 at 08:07
  • Which one you wish to clear: The "Male" word or the text inside the input box? – Dhana D. Nov 10 '22 at 08:37

2 Answers2

1

You can use innerText to find Male text, and use replace (or replaceAll) on innerHTML which will remove text only

const td = document.getElementById("gender3")
td.innerHTML = td.innerHTML.replace(td.innerText.trim(), "")
<table>
  <tr>
    <td id="gender3" name="gender">Male
      <input id="gender_input3" type="text" style="border:ridge;width:90px" name="gender" />
    </td>
  </tr>
</table>

Side note that I removed display: none on the input element for testing purpose.

Nick Vu
  • 14,512
  • 4
  • 21
  • 31
1

If you need to remove nodes being of type text, you can fetch the input parent node (the td element) using the #gender3 selector and list all of its child nodes, removing only nodes being of that type (where .nodeType is 3).

This is a demo that accomplishes that by adding a click event listener to the trigger button that when fired will perform the action described above:

const btn = document.getElementById('action');
btn.addEventListener('click', (event)=>{
  const inputParent = document.getElementById('gender3');  
  //removes all child nodes having nodeType being a text node
  inputParent.childNodes.forEach((o,i)=>{
    if (o.nodeType == 3)
      o.remove();
  });    
});
<table>
    <tr>
      <td id="gender3" name="gender">
        Male
        <input type="text" id="gender_input3" name="gender"> 
      </td>  
    </tr>
 </table>
 
 <button id="action" type="button">Event triggering the change</button>

For the sake of records it would be more appropriate to use a label element instead (bound to the input control) and just select such element and change its text.

Diego D
  • 6,156
  • 2
  • 17
  • 30