skip to Main Content

I want to modify label text but it has an input, in plain javascript I can do below without losing of the input event.

test.oninput = (e) => console.log(e.target.value)
document.querySelector('label').firstChild.textContent = 'Search: ';
<label>
replace me: <input id="test">
</label>

But, is there built-in jQuery function to do this?

$('label').first().text('Search') // ???? the input missing
// $('label').children().first().text('Search') // do nothing
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>
replace me: <input id="test">
</label>

2

Answers


  1. I suggest that you include your text in a span

    test.oninput = (e) => console.log(e.target.value)
    document.querySelector('label span').firstChild.textContent = 'Search: ';
    <label>
    <span>replace me:</span> <input id="test">
    </label>
    $('label span:first').text('Search:');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <label>
    <span>replace me:</span> <input id="test">
    </label>
    Login or Signup to reply.
  2. You can try this:

    $("label").contents().filter(function () {
       return this.nodeType == 3;
    })[0].nodeValue = "Search: ";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search