Home jquery Check for element existence

Check for element existence

Author

Date

Category

Hello.
The page contains a link with id = 'offers'
When you click on this link, the div with class = 'ajax_block' should load.

Problem: how to make it so that when you click this link again, the loaded ajax disappears? (and not added another one of the same)

I tried:

$ ('# offers'). click (function () {
 if (document.getElementsByClassName ('ajax_block')! == null) {// there are such blocks
  $ ('. offers-ajax'). remove ();
 }
 else {// those such blocks do not need to be added
  $ .ajax ({
   url: 'offers.html',
   success: function (data) {
    $ ('. ajax_block'). append (data);
   }
  });
 }
});

Answer 1, authority 100%

if ($ ('*'). is ('. ajax_block')) {
// some code
}
else {
// another code
}

Answer 2, authority 94%

blunt decision in the forehead

if ($ ('. class'). length & gt; 0) {
  // exists
} else {
  // does not exist
}

Answer 3, authority 33%

if ($ ('. testcss'). length) {
 console.log (true);
} else {
 console.log (false);
}
if ($ ('. testcss-no'). length) {
 console.log (true);
} else {
 console.log (false);
} 
& lt; script src = "https://ajax.googleapis.com/ajax/libs /jquery/1.2.3/jquery.min.js"></script>
& lt; div class = "testcss" & gt;
 test
& lt; / div & gt; 

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions