Home > Software engineering >  jQuery set firstChild
jQuery set firstChild

Time:08-27

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>

CodePudding user response:

You can try this:

$("label").contents().filter(function () {
   return this.nodeType == 3;
})[0].nodeValue = "Search: ";

CodePudding user response:

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>

  • Related