0

Is there anyway to implement the following using pure javascript?

if ( ! $('body.posts.show').length && ! $('body.posts.edit').length && ! $('body.chunks.create').length) 
{
   // Something here
}
1
  • It's worth pointing out: your selectors are probably more specific than they should/need to be. Commented Dec 26, 2014 at 2:16

3 Answers 3

3

You really want to get a single collection with all those selectors and see if it's empty.

In jQuery, you'd do this:

if ( ! $('body.posts.show, body.posts.edit, body.chunks.create').length ) 

The vanilla Javascript approach isn't much more difficult:

if (!document.querySelector('body.posts.show, body.posts.edit, body.chunks.create')) {

See the MDN documentation for document.querySelector.

Sign up to request clarification or add additional context in comments.

5 Comments

What is the browser support
@Anam See the bottom of the page I link. It works in any version of Chrome, FF 3.5+, IE 8+. If you need to support IE <8, I suggest you use a library to help you. jQuery, perhaps!
nice one!! I missed to notice single line way of accessing the inner elements. But querySelector will only the first occurrence of the element, so it has to be querySelectorAll in order to fetch multiple elements.
@Praveen But we're checking to find if there are no elements. So we don't care if there's more than one: if we've found one, we don't need to keep checking. Also, you're very unlikely to have more than one body element in a page!
But we're checking to find if there are no elements valid point :)
1

Yes!! I would suggest to go with querySelector and querySelectorAll methods.

var body = document.querySelector('body');
var posts = body.querySelector('posts');
var chunks = body.querySelector('chunks');
var show = posts.querySelectorAll('show');
var edits = posts.querySelectorAll('edit');
var create = chunks..querySelectorAll('create');

if ( !show.length && !edit.length && !create.length) {
 // Something here
}

Comments

1

You could use Javascript document.querySelectorAll('')! try this

if (!document.querySelectorAll('body.posts.show').length && !document.querySelectorAll('body.posts.edit').length && !document.querySelectorAll('body.chunks.create').length) 
{
  // Something here
}

even better would be

if (!document.querySelectorAll('body.posts.show, body.posts.edit, body.chunks.create').length) 
{
  // Something here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.