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