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() {...})
(is 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>
Since the element was created only after executing the function jQuery has no way to 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
(is 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>
I am not clear what is the expected result.
– rray
It wasn’t clear what you were trying to do @Josimara. What would be catching? To obtain the value of the attribute, the second argument in the function is unnecessary, and there is no property
itemprop
inteste
.– BrTkCa