uingtea
uingtea

Reputation: 6534

jQuery set firstChild

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>

Upvotes: 0

Views: 55

Answers (2)

Paos
Paos

Reputation: 673

You can try this:

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

Upvotes: 2

SKJ
SKJ

Reputation: 2326

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>

Upvotes: 0

Related Questions