tags:

views:

46

answers:

3

is it possible to do an append without specifying a selector

so in html I have an arbitrary element and inside that I call a function that will append content inline

so html looks like this

  <!-- stuff before -->
    <fieldset>
        <script type="text/javascript">
                $(document).ready(function(){
                    get_content();
                });
        </script>
    </fieldset>
  <!-- stuff after -->

then in a js file that gets loaded I have the get_content() function like this

  function get_content(){
        $.append('<div id="some_id"></div>');
  }

currently I get an error saying append is not a function

A: 

It's not very pretty but I guess you could do this;

function get_content(){
  document.write($('<div><div id="some_id"></div></div>').html());
}
Simon
A: 

In the old days this would be accomplished by document.write():

  <!-- stuff before -->
    <fieldset>
        <script type="text/javascript">
           document.write(get_content());
        </script>
    </fieldset>
  <!-- stuff after -->

function get_content(){
  return '<div id="some_id"></div>';
}

But really document.write is not the way jQuery works. Try this way:

function get_content(){
  return 'your real content';
}
$(document).ready(function(){
    $('#some_id').html(get_content());
});


  <!-- stuff before -->
    <fieldset>
       <div id="some_id"></div>
    </fieldset>
  <!-- stuff after -->
artlung
A: 

JavaScript won't write out code in the way you're trying to do it here. JavaScript is separate from content and works with the entire document, so placing JavaScript in your markup where you want it to appear won't do anything unless you use document.write(...), which is considered one of the worst things you can use in JavaScript.

Instead, you should do this:

Your markup would look like this:

<!-- stuff before -->
<fieldset id="elementToAppendTo">

</fieldset>
<!-- stuff after -->

Then your script could look like this (it can go anywhere)

<script type="text/javascript">
$(document).ready(function(){
    get_content();
});
</script>

And then you can use your get_content() function to append stuff.

function get_content(){
    $("#elementToAppendTo").append('<div id="some_id"></div>');
}
Dan Herbert
hmm was trying not to use id or class but looks like that is the best option
mcgrailm