Home > front end >  Clear text only when the outer dom contains text and another dom
Clear text only when the outer dom contains text and another dom

Time:11-10

  <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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related