JS beginner here.
I need help with a script to place different content in a div depending on whether the page body tag has a class of "home" or not.
I am trying to use .hasClass & .html to achieve this. It seems like it should be extremely straightforward, but I can't figure it out. Lack of proper syntax knowledge? Incorrect declarations? I don't know, and am hoping someone can point me in the right direction!
if ($("body").hasClass("home") == true) {
("#mobilemenu").html("<a href="#">HOME</a>");
}
else {
("#mobilemenu").html("<a href="#">NOT HOME</a>");
}
the JSFiddle (which currently does nothing) is here: http://jsfiddle.net/aqyN4/
Links to other JSFiddles or questions with similar functions extremely welcome!
Thank you,
Ali
Use the classList. contains() method to check if the body element has a specific class, e.g. document. body. classList.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
Use the classList. add() method to add a class to the body element, e.g. document. body. classList.
you forgot $
before ("#mobilemenu")
:
if ($("body").hasClass("home")) {
$("#mobilemenu").html("<a href='#'>Alle Kategorien- HOME</a>");
}
else {
$("#mobilemenu").html("<a href='#'>NOT HOME</a>");
}
demo : http://jsfiddle.net/aqyN4/4/
hasClass already tests for a true value, you don't need to make a comparison.
Also, the ("#mobilemenu")
tags did not have jQuery's $
appended. This makes it an undeclared function. Also...you cannot open a statement with "
and use it to encase strings unless you escape it, or use apostrophes. See working code below.
if ($("body").hasClass("home")) {
$("#mobilemenu").html("<a href='#'>HOME</a>");
}
else{
$("#mobilemenu").html("<a href='#'>NOT HOME</a>");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With