Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace only the text of a node, ignoring current internal nodes

I have some HTML:

<label>Search:
  <input id="search-box" type="text"/>
</label>

If I want to change the words "Search:" to "Quick Search:", how can I select just the "Search:" text using jQuery/JS?

I have tried html(), text(), and other various jQuery methods. My goal is to NOT have to copy the input box and then append it after. Is it possible?

P.S. I know I can use the prepend() function, but my goal here is to replace that text entirely, and I'd like to know how to do this in the future as well.

Thanks a bunch.

like image 289
dmcmulle Avatar asked Jan 30 '26 12:01

dmcmulle


1 Answers

If you have access to the HTML I'd wrap the text in a span so that you can address it easily. However, with what you have so far you can simply iterate over all nodes in the element and change the textContent of the first text node (nodeType==3):

$(function(){
    
    $("label").contents().each(function() {
        if(this.nodeType == 3){
            this.textContent = "Quick Search: ";
            return false;
        }
    })
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Search:
  <input id="search-box" type="text"/>
</label>
like image 94
Moob Avatar answered Feb 01 '26 01:02

Moob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!