How to use onload in DIV elements?

1

I'm setting some similar functions for different pages on a website. Therefore, these functions are in the same file. When the JS file is loaded the $(function() { /*function1*/ }); and $(function() { /*function2*/ }); functions are executed. However, the elements I get via jQuery (eg, $('.elem').val(); ) will not exist because they are on another page.

How do I make a function run only when a determining element is loaded?

    
asked by anonymous 02.08.2014 / 20:52

2 answers

1
___ erkimt ___ How to use onload in DIV elements? ______ qstntxt ___

I'm setting some similar functions for different pages on a website. Therefore, these functions are in the same file. When the JS file is loaded the $('.elem').length and .elem functions are executed. However, the elements I get via jQuery (eg, %code% ) will not exist because they are on another page.

How do I make a function run only when a determining element is loaded?

    
______ ___ azszpr27628

One way to know if an element exists with jQuery is to use the length property. %code% tells you how many elements have on the page that match the selector %code% .

if( $('.elem').length > 0 ){
   //tem nós da classe elem no documento
}else{
   //nao tem
}
    
______ azszpr27650 ___

Depending on the operations you want to do with the element (s), it is best to use $ .each so you can reference each one of them with $ (this) or with the parameter variables. p>

Ex:

if( $('.elem').length > 0 ){
   //tem nós da classe elem no documento
}else{
   //nao tem
}

HTML

%pre%     
___
02.08.2014 / 21:33
1

Depending on the operations you want to do with the element (s), it is best to use $ .each so you can reference each one of them with $ (this) or with the parameter variables. p>

Ex:

$(".layout_cron").each(function(index, element) {
    if ($(this).data("elemento")) elemento = $(this).data("elemento"); else elemento = "#" + $(this).attr("id");
    cronometro_regressivo($(this).data("agora"), $(this).data("fim"), elemento);
});

HTML

<div id="header_banner_cron" class="layout_cron" data-agora="1407032260" data-fim="1407553140" style="position:absolute;left:197px;top:0px;"></div>
    
03.08.2014 / 04:19