Links from the database are website titles and render on the page "Interesting Article: Author" - but occasionally the link is a question "Where's China?: GoogleMaps". The ?:
looks silly so I wanted to replace the HTML ?</span>:
with ?</span>
.
Here is the jQuery I worked out:
$('#relatedinfo ul li a').html().replace('?</span>:','?</span>');
But this doesn't actually replace it in the DOM. How do I get that string to actually change the page?
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
To change text inside an element using jQuery, use the text() method.
I'd suggest:
$('#relatedinfo ul li a').html(function(index,html){
return html.replace(/<\/span>(\:)/,'');
});
JS Fiddle demo.
Or even:
$('#relatedinfo ul li a').text(function(index,text){
return text.replace(':','');
});
JS Fiddle demo.
An updated approach is to check that the last character in the span
is in the array of ['?','!','.']
and, if it is, then to remove the :
from the nextSibling's nodeValue:
$('#relatedinfo ul li a span').text(function(index,text){
var lastchar = text.split('').pop();
if (['?','!','.'].indexOf(lastchar) > -1) {
this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(':','');
}
});
JS Fiddle demo.
References:
html()
.String.replace()
.text()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With