Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Detect if a jQuery object is on the page or not

Given a jQuery object, $j, I need to know if it represents something that is already on the page or if it is something that has not yet been put on the page. For example, if I have this:

$j = $('#id-of-something-already-on-the-page');

or

$j = $('<p>Where is pancake house?</p>').appendTo($('#this-is-already-there'));

Then I have something on the page and I don't need to put it on the page. But, if I just have this:

$j = $("<p>I'll cook you some eggs, Margie.</p>");

Then I'd need to append it before it is on the page.

The question is how do you ask $j if it is on the page or not? I know two ways the work well enough:

  1. See if it has a parent: $j.parent().length > 0 implies that it is on the page.
  2. See if it has a valid index: $j.index() > -1 implies that it is on the page.

I can see the first one failing if $j is the html or possibly body; I'm happy to ignore those two pathological cases. I can't think of any way that the second approach would fail.

Is there a standard technique for asking if a jQuery object is on the page or not? I don't care if $j is visible.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Personally, I'd start by descending from an element you know is in the page, like <html> or <body>, and use .has():

if ($('html').has($j).length)
{
    // $j is in the page
}

This works even for the two pathological cases you mentioned. It's more idiomatic to check .length rather than .size(). There's also no reason to check that the value returned is > 0. The length property will always be a nonnegative integer, so it's sufficient to check the truthiness of the value.

over 4 years ago · Santiago Trujillo Relatório

0

I'd probably just check to see if the element can reach the body element:

$j.closest('body').size()>0

As you noted in other comments, this would fail in some exceptional cases where you are handling extra body elements. If you really want to detect those situations, I guess you could check to see if you have multiple $(body) elements but I suspect that such extreme cases will get out of control pretty quickly.

This "is-probably-attached-to-page" check could be turned in to a bona-fide jQuery selector, too:

$.expr[':'].isProbablyAttached = function(obj){

    return $(obj).closest('body').size()>0;
};

// Usage:
$('.someClasses:isProbablyAttached').doSomething();
over 4 years ago · Santiago Trujillo Relatório

0

With jQuery (at least with version 1.7.1) $('html').parent() returns a non-empty array ([#document]):

$j = $("<p>I'll cook you some eggs, Margie.</p>");
$j.parent().length === 0
$('html').parent().length === 1
$('body').parent().length === 1

So 'mu is too short''s note is not an issue:

I can see the first one failing if $j is the html or possibly body; I'm happy to ignore those two pathological cases. I can't think of any way that the second approach would fail.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda