The simple code explains my problem best:
<html>
<head>
<script>
function showDiv (divId, dat){
document.getElementById(divId).innerHTML = dat ;
document.getElementById(divId).style.display = "block" ;
}
</script>
</head>
<body>
<div onclick="showDiv(1, '<div onclick='showDiv(2, 'test C');'>test B</div>')">test A</div>
<div id="1" style="display:none;"></div>
<div id="2" style="display:none;"></div>
</body>
</html>
the argument by onclick function contains a functions with arguments (strings).
doesn’t work like that.
I think the apostrophes are the problem.
pls help. thx
my code above explains my problem best
4
Answers
you can use " for double quotes and ' for single quotes inside "showDiv()"
hope it helps
As mykaf commented,
addEventListener("click", (event) => {});
would achieve the same and is generally neater. So asonclick = (event) => {};
You can still use HTML inline onclick using backticks (`) like so:
<div onclick="showDiv(1, `<div onclick='showDiv(2, 'test C');'>test B</div>`)">test A</div>
It might be easier to hide the elements you don’t want to see in the first instance and then reveal them when their sibling is clicked.
Use a class to hide the elements, and remove the class when you want them shown
Use a data attribute to indicate what element should be shown.
Use event delegation – attach a listener to a parent element, and then listen for events from its children as they "bubble up" the DOM.
If you know that the next element is the one immediately below the one you’re clicking on you can make the markup tidier and the code shorter.
Additional documentation
data attributes
classList
closest
querySelector
nextElementSibling
Your code is cursed but I understand what you’re trying to do. Every time you do a recursive div you need to do these escapes:
JS escape:
"
becomes"
(JS can also use'
and`
, but for simplicity let’s stick with"
) andbecomes
\
HTML escape:
"
becomes"
and&
becomes&
Therefore the code you need is:
<div onclick="showDiv(1, "<div onclick="showDiv(2, &quot;test C&quot;)">test B</div>")">test A</div>
Here’s how you would add a fourth layer!
(This is obviously not very readable — this is why inline JS is not used very often)