John Alabama John Alabama - 1 year ago 72
Javascript Question

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.

I found this code:

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;

and used it in such a way:

<li class="pl11">
<a href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="">superlink</a>')">Pomorskie</a>

And it doesn't work as I expected.

It changes hyperlinks text from 'Pomorskie' to 'superlink'.

The plain text works just fine but I need links.

here's the (only two of them show anything)

But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/

Thanks a lot for trying, and cheers :)

Answer Source

Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.

Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.

Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.

// Probably better in a separate helpers.js file.
   function replaceContentInContainer(target, source) {
      document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;

Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)

<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>

We have our target somewhere in the document.

<div id="target">My content will be replaced</div>

Then the replacement content sits hidden inside a replacements div.

<div id="replacements" style="display:none">
  <span id="replace_target"><a href="">superlink</a></span>

Here it is in JSBin

Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.

edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download