admin管理员组

文章数量:1334946

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 = '';

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 = '';

Share Improve this question edited Nov 6, 2020 at 15:45 Derek Wang 10.2k4 gold badges19 silver badges40 bronze badges asked Nov 6, 2020 at 15:32 mitsumitsu 4302 gold badges11 silver badges26 bronze badges 2
  • Does this answer your question? Jquery - Remove only text content from a div – AcK Commented Nov 6, 2020 at 17:06
  • @ack no :( :( :( – mitsu Commented Nov 6, 2020 at 17:48
Add a ment  | 

4 Answers 4

Reset to default 3

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]);
});

本文标签: javascriptRemove text from a divStack Overflow