-1

Why is the following code giving an exception?

function SetText(index, text) {
            try {
                $('p')[index].innerHTML = text;
            }
            catch (ex) {
                alert(ex);
            }
        }

        $(document).ready(SetText(2, 'Damn'));

the exception is:

TypeError: $('p')[index] is undefined

This is my code file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SelectingFromAnElementGroup.aspx.cs" Inherits="JQuery_Intellisence_Test.SelectingFromAnElementGroup" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script src="Javascript/jquery-1.3.2.js" type="text/javascript">
        /// <reference path="jquery-1.3.2-vsdoc.js" />
    </script>
    <script type="text/javascript">
        function SetText(index, text) {
            try {
                $('p')[index].innerHTML = text;
            }
            catch (ex) {
                alert(ex);
            }
        }

        $(document).ready(SetText(2, 'Damn'));
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>This is 1st Paragraph</p>
            <p>This is 2nd Paragraph</p>
            <p>This is 3rd Paragraph</p>
            <p>This is 4th Paragraph</p>
            <p>This is 5th Paragraph</p>
        </div>
    </form>
</body>
</html>
1
  • please, show your html code woth 'p' Commented Nov 2, 2009 at 10:27

2 Answers 2

3

Try that and tell us what happens:

$(document).ready(function() { SetText(2, 'Damn') });

I think your function is called before the DOM is ready.

Sign up to request clarification or add additional context in comments.

Comments

0
<html>
<head>
    <script src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("jquery", "1.3.2");
        function SetText(index, text) {
           try {
               if (typeof $('p')[index] !='indefined') $('p')[index].innerHTML = text;
           } catch (ex) {
                alert(ex);
           }
        }
</script>
</head>
<body>
    <p>Paragraph 0</p>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <script type="text/javascript">
        $(function() {SetText(2, 'Damn');});
    </script>
</body>
</html>

Your code needs to be checked by

if (typeof $('p')[index] !='indefined')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.