Remove text from a div

Viewed 1402

I am looking for a way to remove a text from a div, without removing the button inside. Please see the image above.

The following code does not work because it removes the button too.

$(".input-group-append").empty();

OR

document.querySelector(".input-group-append").text = '';
document.querySelector(".input-group-append").innerHTML = '';

enter image description here

4 Answers

Since you are not planning to remove the button itself and just want to remove the text within the button, you must modify the seclector to direct towards the button itself and then use text or innerText property.

document.querySelector(".input-group-append > button").text = '';

// OR

document.querySelector(".input-group-append > button").innerText = '';

This will remove the text from within the button.

To remove the text, you can store the children selectors first and clear the parent with innerHTML='' and add that children selectors again.

const parent = document.querySelector(".input-group-append");
const childs = [];
for(let i = 0; i < parent.children.length; i ++) {
  childs.push(parent.children[i]);
}

parent.innerHTML = '';
childs.forEach((item) => parent.appendChild(item));
<div class="input-group-append">
  <button type="submit" class="btn btn-search">Submit Button</button>
  Test Text
</div>

For this use case could probably just do,

el = document.querySelector('.input-group-append')
for (let i = 0;i<el.children.length;i++) {
  if(el.childNodes[i].nodeType === 3) {
    el.removeChild(el.childNodes[i])
  }
}

This shoud remove all loose text from your div without touching elements:

var elements = $(".input-group-append *");
$(".input-group-append").html("");
elements.each(function(){
  $(".input-group-append").append($(this)[0]);
});
Related