I’m building a WordPress blog. I faced an issue so I wrote below JavaScript code just so I can hide the element according to the text it has. If element don’t have any text, It should be hidden. If it has text, it should be visible (which it is already).
For better understanding, please look at the HTML of the problem here.
function btnHidingWordPress(){
// targets spans containing text
let CalendarPrevBtn = document.getElementsByClassName('wp-calendar-nav-prev');
let CalendarNextBtn = document.getElementsByClassName('wp-calendar-nav-next');
// stores spans text
let PrevBtnText = CalendarPrevBtn[0].textContent;
let NextBtnText = CalendarNextBtn[0].textContent;
// deciding if btn needs to be hidden
Array.from(CalendarPrevBtn).forEach((x) => {
if (PrevBtnText == ' ') {
CalendarPrevBtn.style.display ="none";
}
else {
CalendarPrevBtn.style.display ="block";
})
Array.from(CalendarNextBtn).forEach((x) => {
if (NextBtnText == ' ') {
CalendarNextBtn.style.display ="none";
}
else {
CalendarNextBtn.style.display ="block";
})
}
btnHidingWordPress();
Whenever I run this code, instead of hiding the element (span in my case) it throws a console error saying:
Uncaught SyntaxError: Unexpected token ')'
At this point, i don’t even know what am I doing. I just want to make button hide if it does not contain any string. That’s it.
Regards,
I tried to look into different sources and all pointed that i need to loop CalendarPrevBtn via forEach because getElementByClasssName returns an array (Which is true). So, i don’t know too much theory and it somehow solved other bugs which obviously I didn’t either. Now, I am stuck here. What can be done.
2
Answers
As far as the question goes it’s exactly as @Fcmam5 pointed out (srry writing it as an answer since I can’t comment yet)
Here at the last line the first
}
closes the else statement and next another}
is expected to close the function body. Finally a)
is expected to close the forEach statement. However the second}
is missing.So changing
})
=>}})
in both lines of the lines 18 and 27 will solve the error.There are a few issues in your code that need to be fixed:
Incorrect usage of the forEach loop: You are using forEach on the CalendarPrevBtn and CalendarNextBtn elements, which are not necessary since you’ve already extracted the text content of the first element in each collection.
Incorrect element reference for applying the style: You should use the individual elements (x) inside the forEach loop to apply the style.
Extra closing parenthesis and misplaced closing braces: There is an extra closing parenthesis after the "block" line, and the closing braces are misplaced.
Here’s the corrected code