Reputation: 41
I hope the topic fits the question.
Hey guys excuse my noobness, but I have been cracking my head in trying to solve this problem.
Code:
<a id="123" href="#123" onclick="document.getElementById('chgtext').innerHTML='<a id="1" href="#" onclick="document.getElementById('chgtext_1').innerHTML='Johnss's House';">chapter 1</a>';">Wonderful</a>
<div id="chgtext"> </div>
<div id="chgtext_1"> </div>
What I wanted it to be is to show a link called "Wonderful" and when clicked it will show "chapter 1" and when "chapter 1" is clicked it will show "Johnss's"
I have tried escaping it all with \
but doesn't work.
If possible I would like it to remain as this method, but if this method doesn't work then is there any method out there.
Ohh and the whole link
<a id="123" href="#123" onclick="document.getElementById('chgtext').innerHTML='<a id="1" href="#" onclick="document.getElementById('chgtext_1').innerHTML='Johnss's House';">chapter 1</a>';">Wonderful</a>
is output from php server side to HTML to echo it out. That's why it's in a one line code
Thank you
Upvotes: 0
Views: 9569
Reputation: 58422
I would use event handlers and bind the events using js rather than in the html, this way, you can delegate an event for the dynamic object that hasn't been created yet
// bind a normal event to the first link:
var link = document.getElementById('123');
link.addEventListener('click', function (e) {
e.preventDefault(); // as the target is a link you want to prevent the default action of it
document.getElementById('chgtext').innerHTML = '<a id="1" href="#">chapter 1</a>';
});
// the following is a delegated event - you bind it to an existing element (in this case the document) and then check that the target being clicked is the new element that has been dynamically created
document.addEventListener('click', function (e) {
// check the id of the clicked element
if (e.target.id == 1) {
e.preventDefault(); // as the target is a link you want to prevent the default action of it
document.getElementById('chgtext_1').innerHTML = 'Johns\'s House';
}
});
<a id="123" href="#123">Wonderful</a>
<div id="chgtext"> </div>
<div id="chgtext_1"> </div>
Upvotes: 0
Reputation: 33
Try this
<!DOCTYPE html>
<html>
<body>
<a href="#" onclick="main()">Wonderful</a>
<p id="main"></p>
<p id="sub"></p>
<script>
function main(){
document.getElementById("main").innerHTML =
"<a href='#' onclick='sub()'>Chapter 1</a>";
}
function sub(){
document.getElementById("sub").innerHTML =
"Johnss's";
}
</script>
</body>
</html>
Upvotes: 1