Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If body has this class, then place this content in #mydiv, else place other content in #mydiv

Tags:

jquery

class

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

like image 762
Ila Avatar asked Jul 06 '12 15:07

Ila


People also ask

How do you know if your body contains class?

Use the classList. contains() method to check if the body element has a specific class, e.g. document. body. classList.

How do you check if an element has a specific class in jQuery?

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".

How do you add a class to your body in HTML?

Use the classList. add() method to add a class to the body element, e.g. document. body. classList.


2 Answers

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/

like image 92
mgraph Avatar answered Sep 24 '22 06:09

mgraph


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>");
}
like image 36
Ohgodwhy Avatar answered Sep 26 '22 06:09

Ohgodwhy