Jquery attr function does not work

Asked

Viewed 256 times

0

I created the attr function in jquery but this does not take 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>
  • I am not clear what is the expected result.

  • 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 in teste.

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() {...}) (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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.