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>