简体   繁体   中英

How to use jQuery and JavaScript accurately find if an element exists

I've read several posts about this but it simply does not work for me. I'm using Ruby on Rails as my MVC framework. I add classes to my body tag mapping to the controller and action .

<body class="<%= controller_name %> <%= action_name %>">

So on a controller home action about I might have

<body class="home about">

Rendered by the server and sent to the client. I want to have page specific JavaScript but I can't seem to do it correctly.

I've tried this but it always returns true

var page = $('body.home')

if (page) {
  console.log('Right page')
} else {
  console.log('Wrong page');
}

// returns 
// jQuery.fn.init [prevObject: jQuery.fn.init(1), context: document, selector: "body.information"]

I've tried this but it always returns true

var page = $('body.home')[0]

if (page) {
  console.log('Right page')
} else {
  console.log('Wrong page');
}

I've tried this but it always returns true

var page = $('body.home')[0]

if ($(page)) {
  console.log('Right page')
} else {
  console.log('Wrong page');
}

I've tried this but it always returns false

var page = $('body.home')[0]

if ($(page).length > 0) {
  console.log('Right page')
} else {
  console.log('Wrong page');
}

So when I'm on the correct page(a page with element body that has class home) it console.logs 'Wrong page'

To check for a class, you need to use classList.

Like so:

Plain javascript.(classList.contains only works in mordern browsers);

  let body = document.getElementsByTagName('body'); console.log(body[0].classList.contains('one')); console.log(body[0].classList.contains('two')); 
 <body class="one tow"> </body> 

You can also do:

 let body = document.getElementsByTagName('body') let isClassThree = body[0].className.split(" ").indexOf('three') let isClassFour = body[0].className.split(" ").indexOf('four') console.log(isClassThree, isClassFour) 
 <body class='two three'> </body> 

JQuery: $("body").hasClass(className)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM