Midhun Mathew
Midhun Mathew

Reputation: 2207

jQuery working in console but not in original code

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>

Upvotes: 14

Views: 28654

Answers (6)

Jaggan_j
Jaggan_j

Reputation: 518

The order of your jQuery files in the master layout page can also influence why it does not work in actual code but works in console of the browser. jQuery files must be referenced in the following order in the master page:

<script type="text/javascript" src="/Scripts/jquery-3.1.1.min.js"></script>      
<script type="text/javascript" src="/Scripts/jquery-ui-1.12.1/jquery-ui.min.js"></script> 
<script type="text/javascript" src="/Scripts/bootstrap.min.js"></script>

For people coming here looking for a solution to what it says in title without going into specifics of this particular question, hope it helps someone.

Upvotes: 0

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/

Upvotes: 22

Stefan
Stefan

Reputation: 3041

The JS is firing before the html is created.

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

Upvotes: 6

DarkAjax
DarkAjax

Reputation: 16223

Your code executes before the DOM is ready and the element actually exists, try it this way:

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

The reason it works on console is because the <a> element already exists when you execute your code...

JSBin Demo

Upvotes: 4

Jeremy Gallant
Jeremy Gallant

Reputation: 774

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

Upvotes: 7

user
user

Reputation: 545

put it in a ready section :

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

Upvotes: 4

Related Questions