Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Replace Text in an Element [closed]

I've been working now for a while on the javascript process and can't really figure out on how to do this. I know how to basically tell javascript to set a certain value for a specific ID. But my Problem here is: I'd like to write javascript to read out information (Server based, but that I'll do by myself ofc.) set it as var and then write it into text. It should look like this in the end:

Before writing (Without Javascript):
<h1 id="name" class="normal">Welcome, %Name%! What do you wish to do?</h1>

After writing (With Javascript):
<h1 id="name" class="normal">Welcome, John Connor! What do you wish to do?</h1>

So basically what I thought of is, that JS reads out information from server, then finds the h1 ID, searches in that text the %Name% value, and replaces it with the found name.

Please help me out here.Thanks!

Best Regards Kodaigan

like image 963
Kodaigan Avatar asked Feb 16 '26 16:02

Kodaigan


1 Answers

If using jQuery:

$('#name').html(function(index, html){
    return html.replace('%Name%', yourVariable);
});

Pure javascript:

document.getElementById('name').innerHTML = document.getElementById('name').innerHTML.replace('%Name%','John');

This will replace a given string inside your h1 element.

like image 71
Shambhavi Avatar answered Feb 18 '26 04:02

Shambhavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!