How to Verify the existence of an Id in a document via Jquery?

Asked

Viewed 2,059 times

2

I am programming the system of my TCC and in it I am creating a site that contains two types of ID in the Div container of each page: fundo_index on the Index and fundo_base in other pages.

I need to do a check to know which of these Ids exists to thus trigger a function specific only for Index, as I am using Jquery, I searched and found the method.hasClass(); that checks the classes of an element, but I couldn’t find its equivalent for Ids.

I would like to ask you what is this equivalent of this method for Ids and if it doesn’t exist, what is the way to do this verification?

4 answers

4

Use $(seletor).length to verify the amount of elements that give match according to the selector. A id is unique per document, so the value obtained by calling length may only be: 1 in case the element is present in html or 0 if there is no.

$(function(){
  if($('#fundo_index').length)
    console.log('tem #fundo_index');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='fundo_index'>
  <!-- ... -->
</div>

2


var existeFundoIndex = document.getElementById('fundo_index');

This is the way to know if there is an element on the page with the ID fundo_index. It’s pure, native Javascript. For simple things like this you don’t need jQuery.

If the element exists then the variable will have a pointer to that element, that is to say it will have bolean value true, if it does not exist it will have the value null.

You can make logic around it, or test other elements. For example:

var existeFundoIndex = document.getElementById('fundo_index');
if (existeFundoIndex){
   // fazer algo
} else {
   // fazer outra coisa
}

Or else:

var existeFundoIndex = document.getElementById('fundo_index');
var existeFundoBase = document.getElementById('fundo_base');
if (existeFundoIndex){
   // fazer algo
} else if (existeFundoBase) {
   // fazer outra coisa
} else {
  alert('Não há nenhum!...);
}

Or any other variant you need...

More info:

  • 1

    worked here, vlw ae, didn’t think it would be so easy

2

You don’t necessarily have to use jQuery for that

if(document.getElementById('fundo_index'))
    //elemento com id "fundo_index" existe
else
    //elemento com id "fundo_index" não existe

0

You can use the has-attribute. After all, the ID is an attribute anyway.

In this link is the example: Has Attribute

  • 1

    yes, but how to do this on all page elements to check if one of them has the attribute id?

Browser other questions tagged

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