var parentElementDiv = document.getElementById(parentElement);
var exampleElement = document.querySelector('#' + parentElement + ‘.example’);
Let’s talk a bit about what just happened here. So we declared a variable named ‘parentElementDiv’ and assigned it to the result of a function named getElementById, which was called from the document object. The document object simply references everything we can see on our webpage. It is literally the webpage document. The getElementById method that we are calling, will search through the document (webpage) and look for an element with the id that we pass to it. In this case, it will find the element with the ‘tables’ id. (Notice how we don’t need to specify the # to denote id here as it is already expecting an id anyway.)
Then we declared a new variable named ‘exampleElement’, which contains the result of the method querySelector(), which is also run from the document object. This function works a bit differently. It’s similar to how we specify elements in Css. We pass in a query to find the element we are looking for. In this case, because we only want the ‘.example’ div that sits inside of the parent that we passed in, we need to nest it inside the parent’s element, just like we would in CSS. You will notice here that we do need to add ‘.’ and ‘#’ to our query, just like we would in CSS to ensure that we get the result we are looking for.
Now that we have our variables, we can start to make use of them.
Let’s next perform the relevant check to see if the code is already shown on the webpage or not. We can do this by checking for the existence of a class on the parent element that we passed in. Basically we are going to add a class of ‘open’ to the parent div when we click the ‘show code’ button. This way we have a clear indicator that the code is being shown. So let’s detect this in an if statement.