JavaScript – Como saber se um Elemento está Oculto usando o jQuery

Quando estamos utilizando o jQuery no JavaScript, muitas vezes queremos tomar uma ação baseada no estado de um elemento. Um dos estados bastante utilizados é o de se o elemento está visível ou não. Um elemento é considerado visível quando ele ocupa espaço no documento. Elementos visíveis tem altura ou largura maior do que zero.

Para podermos descobrir se um elemento está oculto, temos basicamente duas ferramentas para utilizar. A primeira que vamos utilizar é a :visible.

JavaScript – usando :visible com o jQuery

O seletor :visible verifica se o elemento está visível dentro do DOM.

$(document).ready(function() {
    if($("#content").is(":visible"))
    {
        alert('elemento é visível no DOM');
    }
    else
    {
        alert('elemento não é visível no DOM');
    }
});

Abaixo temos um exemplo utilizando este seletor para determinar uma ação dentro do programa:

<div id="countries">
  <div id="p1">EUA</div>
  <div style="display:none" id="p2">Canada</div>
  <div id="p3">Mexico</div>
</div>

Para checar se a div #countires está visível, use a função is() passando o seletor “:visible”:

if( $('#countries').is(':visible') ) {
  // está visível, faça algo
} else {
  // não está visível, faça algo
}

Loop pelas divs visíveis dentro da div #countries:

$("#countries div:visible").each( function() {
  document.write($(this).html()+'<br />');
});

O resultado acima será:

EUA

Mexico

JavaScript – usando :hidden no jQuery

O seletor :hidden faz a verificação oposta, se o elemento está oculto dentro da DOM

var isHidden = $( "#myDiv" ).is( ":hidden" );

Com esses dois seletores, é possível verificar o estado do elemento e prosseguir com o código baseado na resposta. Você conhece outras maneiras de fazer esta operação no JavaScript?  Compartilhe seus comentários na seção abaixo!

Caso deseje explorar outras questões, pode conferir nossos vídeos sobre JavaScript. Abaixo estão alguns exemplos:

Você também pode se inscrever em alguns canais que fazem broadcast em JavaScript, como os a seguir:

ObsidianBlk

TimMikeladze

Outra maneira legal de descobrir mais coisas interessantes sobre JavaScript é acessar nossa página de projetos!

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

View Comments

Recent Posts

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

2 weeks ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

1 month ago

Highest Stable Coin Yields – (W12 – 2024)

It’s another week and like always we have to explore the top yield platforms for…

1 month ago

Binance Auto Invest – the Best Innovation in Crypto since Sliced Bread

At a time where we’re constantly seeking tools and strategies to simplify our crypto investments,…

1 month ago

Highest Stable Coin Yields – March 2024

As we kick off another week, it's time to explore the top yield platforms for…

2 months ago

Education Ecosystem Featured on Business Insider

We're excited to share that Education Ecosystem was recently featured in an article on Business…

2 months ago