Home > database >  Remove plain HTML text withing a div
Remove plain HTML text withing a div

Time:01-30

How can I remove the 'Currently' in the HTML withouting deleting other texts

<div >
  Currently:  <--- Remove this text
  <a href="/media/images/header-dots.png">images/header-dots.png</a>
  <input type="checkbox" name="profile_picture-clear" id="profile_picture-clear_id">
 
  <input type="file" name="profile_picture" accept="image/*" id="id_profile_picture">
  <p> But don't remove this </p>
  <label for="id_profile_picture">Profile Picture</label>
</div>

CodePudding user response:

You can use a regexp and the innerHTML:

const textContainer = document.querySelector('.group')
const btn = document.getElementById('remove')

const removeText = (el, regexp) => {
  const oldHTML = el.innerHTML
  const newHTML = oldHTML.replace(regexp, '')
  return newHTML
}

const regexp = /Currently:/g

btn.addEventListener('click', function() {
  textContainer.innerHTML = removeText(textContainer, regexp)

})
<div >
  Currently: <!-- Remove this text -->
  <a href="/media/images/header-dots.png">images/header-dots.png</a>
  <input type="checkbox" name="profile_picture-clear" id="profile_picture-clear_id">

  <input type="file" name="profile_picture" accept="image/*" id="id_profile_picture">
  <p> But don't remove this </p>
  <label for="id_profile_picture">Profile Picture</label>
</div>
<button id="remove">REMOVE THE TEXT</button>

CodePudding user response:

You can use the DOM to your advantage. If you have a reference to the parent Div, you can use the childNodes property (https://www.w3schools.com/jsref/prop_node_childNodes.asp) of it. It only returns the HTML elements, and not the text nodes. You could write a pretty simple function that loops through the childNodes to rebuild the innerHTML and by happy side-effect, it would leave out the text nodes.

If you want specific text nodes removed, you can use the children property (https://www.w3schools.com/jsref/prop_element_children.asp) which includes both the text nodes and the html elements. Then you still loop through the children and just add logic to decide if you add it back in to the innerHTML.

  •  Tags:  
  • Related