Home > front end >  Simple jQuery if else statement
Simple jQuery if else statement

Time:11-29

I have a mini script, this script finds within a specific class the link. I basically need a simple if-else-statement. Something like if a is existing, then run the script if not, then do nothing.

Can someone help me with that?

jQuery(document).ready(function() {
  jQuery("body").on("click", ".click-child", function() {
      var href = jQuery(this).find("a").attr('href');
      window.location = href;
  });
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Based on your question, this is what I imagine you're asking for. If you could put your HTML somewhere it would be more clear what you're looking for.

jQuery has a .find() method which searches the parent selector for a child selector, if it finds the child selector, you can use it as a normal jQuery selector. Otherwise, it'll do nothing.

If this isn't what you're looking for, please add a little more detail, and I'll see if I can help your out more.

<section class="cards">
    <div class="card">
        <img />
        <h3>Opens link</h3>
        <a href="https://google.com">Link</a>
    </div>
    <div class="card">
        <img />
        <h3>Nothing should happen</h3>
    </div>
</section>

<script>
    jQuery(window).ready( function() {
        jQuery('.card').click(function() {
            const link = jQuery(this).find('a').attr("href")
            
            if (link) {
                window.location = link;
            }         
        });
    });
</script>

CodePudding user response:

You don't need an if/else. You can do an .each() over a list (which might either contain one element, or be empty):

jQuery(function() {
  jQuery("body").on("click", ".click-child", function () {
    jQuery(this).find("a").first().each(function () {
      window.location = this.href;
    });
  });
});

CodePudding user response:

You can use the :has() selector to only hook the event handler to the .card elements which contain an a. Then you don't need the if statement at all. Try this:

jQuery($ => {
  $("body").on("click", ".click-child:has(a)", function() {
    var href = $(this).find("a").attr('href');
    window.location = href;
  });
});
  • Related