How to check whether or not there is a rel=""

Asked

Viewed 367 times

1

I’m mounting a function for wordpress, in which one can navigate between the posts through the Keyboard.

With difficulties, I managed to create the following function:

   <script>
        window.onkeydown = function(event) {
            if (event.keyCode === 38) { //Para cima

                if($(window).scrollTop() == 0) { 
                    var href =  $("a[rel='next']").attr("href");                 
                    window.location.href = href;
                }

            }
            if (event.keyCode === 40) { //Para baixo

                if($(window).scrollTop() + $(window).height() == $(document).height()) { 

                    var href =  $("a[rel='prev']").attr("href");                 
                    window.location.href = href;
                }
            }            

        };
    </script>

However, I needed to check first if there is a rel="Prev" or rel="next" in html to release or not the keydown function

for example:

If there is a rel="prev" html, then run the page change function by pressing the button on the keyboard.

Thanks in advance for the help

1 answer

1

You can try to get the element using jQuery, if it is different from null it is because the element exists.

Example

//para executar apos o DOM ser carregado
$(document).ready(function(){
   let prev = $('[rel="prev"]'),
       next = $('[rel="next"]');

   if (prev.length) console.log("Tem prev");
   if (next.length) console.log("Tem next");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input rel="prev">

  • Hello @Ucas coast, thank you, but I got it in a simpler way: if ($("a[rel='Prev']"). length > 0) {

  • 1

    Good! It’s basically the same thing @Thallysondias actually if (prev.length) is simpler than if ($("a[rel='prev']").length > 0), as you can see here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.