Reputation: 3341
I'm trying to append two different templates to two separate div containers respectively. But both templates are applying only to the first DIV container.
<!DOCTYPE html>
<html>
<body>
<div id="cont1">
</div>
<div id="cont2">
</div>
<button onclick="showSection('container1', true)">Container1</button>
<button onclick="showSection('container2', true)">Container2</button>
<template id="container1"><p>This should be in container1</p></template>
<template id="container2"><p>This should be in container2</p></template>
</body>
<script>
function showSection(templateId,repeat){
var temp = document.getElementById(templateId);
var clon = temp.content.cloneNode(repeat);
if(templateId="container1"){
var divId = "cont1"
var position = document.getElementById(divId);
position.appendChild(clon);
}
if(templateId="container2"){
var divId = "cont2"
var position = document.getElementById(divId);
position.appendChild(clon);
}
}
</script>
</html>
Yet:
What am I missing?
Upvotes: 0
Views: 127
Reputation: 1476
Quite simple actually, I think you might kick yourself ;)
It's as simple as changing:
if(templateId="container1"){
to
if(templateId=="container1"){
Using =
and using ==
mean two very different things.
Single = is an assignment operator and will always equate to true in an if statement (assuming it is a non negative value).
Double or tripple =, as in == and ===, is a comparison and will equate to true only if the values on either side of the operator are equal.
You can find a new working exmaple below
You'll see I've also changed the second if
to an else if
, this is just to make your code a little bit more efficient, more readable, and will probably yeild 'truer' results to what you're trying to achieve but is not necessary
<!DOCTYPE html>
<html>
<body>
<div id="cont1">
</div>
<div id="cont2">
</div>
<button onclick="showSection('container1', true)">Container1</button>
<button onclick="showSection('container2', true)">Container2</button>
<template id="container1"><p>This should be in container1</p></template>
<template id="container2"><p>This should be in container2</p></template>
</body>
<script>
function showSection(templateId,repeat){
var temp = document.getElementById(templateId);
var clon = temp.content.cloneNode(repeat);
if(templateId=="container1"){
var divId = "cont1"
var position = document.getElementById(divId);
position.appendChild(clon);
} else if(templateId=="container2"){
var divId = "cont2"
var position = document.getElementById(divId);
position.appendChild(clon);
}
}
</script>
</html>
Upvotes: 1