Attr function jquery does not work [closed]

0

I created the attr function in jquery but is not picking up what would be the reason?

<script src="https://code.jquery.com/jquery-1.11.3.js"></script><script>$("#teste" ).attr( "itemprop", "name" );

</script>

<div id="teste">
    aaaaaaaaaaaaa
</div>
    
asked by anonymous 22.03.2017 / 21:11

1 answer

2

The element does not yet exist in the order you called, to check if the page has already been completely rendered use $.ready(function() {...}) or simply $(function() {...}) (it's a shortcut to .ready )

<script src="https://code.jquery.com/jquery-1.11.3.js"></script><script>$(function(){$("#teste" ).attr( "itemprop", "name" );
});
</script>

<div id="teste">
    aaaaaaaaaaaaa
</div>

As the element was created only after executing the function, jQuery can not find a test example:

Does not work, returns zero (0):

<script src="https://code.jquery.com/jquery-1.11.3.js"></script><script>console.log($("#teste" ).length);
</script>

<div id="teste">
    aaaaaaaaaaaaa
</div>
If you use onload or DOMContentLoaded (faster) or $.ready (equivalent to DOMContentLoaded ) then they will put the function to wait for the page to be loaded, a test, returns one (1):

<script src="https://code.jquery.com/jquery-1.11.3.js"></script><script>$(function(){console.log($("#teste" ).length);
});
</script>

<div id="teste">
    aaaaaaaaaaaaa
</div>
    
22.03.2017 / 21:14