Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery working in console but not in original code

Tags:

jquery

I have tried the following code to add href to the a tag inside a td. it is working fine while i do in console. But when I try the same in my code it is not working. Can anyone tell me the reason?

<script>
    $("table tbody tr td a").attr('href','http://www.google.com');
 </script>
<table>
    <tr>
        <td><a >Hai</a></td>
    </tr>
</table>
like image 235
Midhun Mathew Avatar asked Jul 15 '13 17:07

Midhun Mathew


2 Answers

Use document.Ready()

$(document).ready(function() {
    $("table tbody tr td a").attr('href','http://www.google.com');
});

You need to ensure that the document is already loaded before you try to manipulate the DOM.

More info: http://api.jquery.com/ready/

like image 66
Guilherme de Jesus Santos Avatar answered Oct 14 '22 15:10

Guilherme de Jesus Santos


The element doesn't exist when your jquery is executing. You need to put your handlers inside a ready function.

<script type="text/javascript">
$(function() {
    $("table tbody tr td a").attr('href','http://www.google.com');
});
</script>

$(function() {}); is the shorthand for $(document).ready(function() {});

like image 45
Jeremy Gallant Avatar answered Oct 14 '22 13:10

Jeremy Gallant