Reputation: 25
I have this code:
<label class="hulkapps_check_option">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
I need to find the text ".00" in the label and replace it with " MXN" but without affecting the input. Whenver I try anything to replace the text it removes the input inside the label. How can I replace a piece of text in the label, without removing the input inside of it?
Upvotes: 1
Views: 841
Reputation: 56744
This would be a way to achieve your goal using the standard Javascript DOM API:
const label = document.querySelector('.hulkapps_check_option');
const labelTextNode = label.childNodes[2];
label.removeChild(label.childNodes[2]);
label.appendChild(new Text(labelTextNode.wholeText.replace('.00', 'MXN')));
<label class="hulkapps_check_option">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
Upvotes: 0
Reputation: 28611
The first option is it put your text inside a <span>
, then it will be easily accessible from jQuery. jQuery isn't designed to handle text-only nodes very well.
If you can't change the HTML for whatever reason, then you can use .contents()
and .this.nodeType === 3
(where 3 is a text node).
$('.hulkapps_check_option').contents().each(function() {
if (this.nodeType === 3) {
this.textContent
? this.textContent = this.textContent.replace(/\.00/g, " MX")
: this.innerText = this.innerText.replace(/\.00/g, " MX")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hulkapps_check_option">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
You could use .html()
to get the text with the input.
While this works in this scenario - it's too brittle to work in the general case (eg if you wanted to change all "put" with "POST" then you'd get <inPOST type="checkbox"
).
You also lose any events you might have had against any elements inside the label.
var h = $(".hulkapps_check_option").html().replace(/\.00/g, " MXN");
$(".hulkapps_check_option").html(h);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hulkapps_check_option_before">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
<hr/>
<label class="hulkapps_check_option">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
Upvotes: 1
Reputation: 199
You can use below code, I just check its working for me.
$(".hulkapps_check_option").text(function() {
return $(this).text().replace(".00", " MXN");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hulkapps_check_option_before">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
<hr/>
<label class="hulkapps_check_option">
<input type="checkbox" data-price="4000.00">
Basic banner design (+$ 4000.00)
</label>
Upvotes: 0