I write a script for one page for a specific element.

On another page, it is missing, and climbs errors. Found a way to bypass errors by checking the presence of the element in this way:

var el = $(".el").html(); if (!el) { console.log('Нет элемента'); } else { console.log('Есть элемент'); }; 
 .el { font-weight: bold; padding: 15px; font-size: 20px; color: #fff; text-shadow: 0 0 5px #125415; display: block; position: absolute; background: #43A047; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="el">Элемент</div> 
If the if / else suits me, then the first line of the script seems to be long, maybe there is a way to write it differently?

  • one
    $('.el').length; - Alexey Shimansky
  • @ Yevgeny Shevtsov. The fact is that an element can return emptiness '' , I would try this if (typeof($(".el").text()) != undefined) { console.log('Нет элемента'); } if (typeof($(".el").text()) != undefined) { console.log('Нет элемента'); } - perfect

3 answers 3

You can use length to see if the selector matches something or not.

 exist = $('#MyId').length; 
  • you can ask, why does the empty element have a length property equal to one? - perfect
  • one
    @perfect length does not return the number of characters inside an element. length returns the number of elements on the page with the specified selector. And once there is an element on the page, even an empty one - accordingly, it will return a unit .......... for example, if you create five divs <div class="el"></div> and write console.log($('.el').length); That will display the number 5. For 5 elements with the specified class on the page is exactly. And what's inside is already the tenth thing - Alexey Shimansky
  • If we are looking for an element without attributes, will it work? - perfect
  • @ Alexey Shimansky, can you write a check using the example of my code? either the if else condition does not work for me or it gives an error if I delete the html element at all, but I just need to get rid of the errors - Evgeny Shevtsov
  • @ AlekseyShimansky, this is exactly the same as in your comments and wrote, and the mistake - Evgeny Shevtsov

This is done like this:

 $("div").is(".el") 
     el ? console.log('Есть элемент') : console.log('Нет элемента'); 

    That is, if, of course, one operator per option yes / no. If more - then your design.

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky
    • console.log (el? "there is": "no") - ikerya
    • that's better - agree - Maxx Out