1

i am trying to append to a div with an ID that is dynamic

                <script>
                    var GameId = "{{$match['gameId']}}";
                    var Ts = '{{$match['createDate']}}';
                    var TsInt = parseInt(Ts);
                    var timeSinceGame = moment(TsInt).fromNow();
                    $('#'+GameId).append(timeSinceGame );
                </script>

the script is run inside of a php foreach loop.

the div ID is set the same as GameID variable however nothing is appended to anything when run what's wrong here?

1 Answer 1

1

None of your jQuery is wrapped in DOM ready events, so the elements are likely not in the DOM yet when the code runs.

Try adding a DOM ready wrapper:

<script>
    $(function(){
        var GameId = "{{$match['gameId']}}";
        var Ts = '{{$match['createDate']}}';
        var TsInt = parseInt(Ts);
        var timeSinceGame = moment(TsInt).fromNow();
        $('#'+GameId).append(timeSinceGame );
    });
</script>

$(function(){ is just a handy shortcut for $(document).ready(function(){

The alternative is to simply inject your code after the elements in the page, so that they do already exist.

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

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.