Reputation: 69
I have this code:
<div>Text: <a href="#">Fly London</a></div>
I want to change the text "Text:" with JS, so I used this:
<script>
$(document).ready(function(){
$('.p-detail-info > div:contains("Text:")').text('Another text:');
});
</script>
But if I do it, the URL will disappear. How to change it if I want to keep URL?
Thank you!
Upvotes: 1
Views: 50
Reputation: 71
You can also do this by simply add span tag and change the span tag text
$(document).ready(function(){
$('.p-detail-info > div > span:contains("Text:")').text('Another text:');});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div class="p-detail-info">
<div><span>Text:</span> <a href="#">Fly London</a></div>
</div>
Upvotes: 2
Reputation: 338
Following should work fine for changing the text:
<script>$(document).ready(function(){$('.p-detail-info > div').text('Another text:');});<script>
Cheers, Happy coding.
Upvotes: 1
Reputation: 370679
You'll have to select the text node, which is not possible with selectors alone, unfortunately. Select the parent div
, get its first childNode
(which is the text node we want), and then assign to the text node's textContent
, no jQuery required:
document.querySelector('div').childNodes[0].textContent = 'Another Text';
<div>Text: <a href="#">Fly London</a></div>
Upvotes: 1