How to check for an ID in a document via JQuery?

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 container container of each page: fundo_index in Index and fundo_base in other pages.

I need to do a check to know which of these IDs exists so to trigger a specific function only for the Index, as I am using JQuery, I searched and found the .hasClass(); method that does this check in the classes of an element, however I could not find the equivalent of it for IDs.

I would like to ask you what is the equivalent of this method for IDs and if it does not exist, what is the way to do this verification?

    
asked by anonymous 08.11.2016 / 19:32

4 answers

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

This is the way to tell if there is an element on the page with the ID fundo_index . It's pure, native JavaScript. For simple things like this you do not need jQuery.

If the element exists then the variable will have a pointer to that element, ie it will have boolean 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:

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 another variant you need ...

More info:

08.11.2016 / 19:36
4

Use $(seletor).length to check the amount of elements that according to selector switch. A id is unique per document, so the value obtained when calling length can only be: 1 in case the element is present in html or 0 if it does not exist.

$(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>
    
08.11.2016 / 19:52
1

You do not necessarily need to use jQuery for this.

if(document.getElementById('fundo_index'))
    //elemento com id "fundo_index" existe
else
    //elemento com id "fundo_index" não existe
    
08.11.2016 / 19:37
0

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

This link has the example: Has Attribute

    
08.11.2016 / 19:38