简体   繁体   中英

Remove text from a div

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

在此处输入图片说明

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.

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM