john smith
john smith

Reputation: 11

Store contents of a tag in Javascript variable

I am learning Javascript and I am trying to learn some pretty basic stuff. Basically I have some text in a <p> tag which I want to append to a variable. However it is not working an I'm not sure why. Any help will be greatly appreciated.

<html>

<head>
<script type="text/javascript" src="js/jquery.js"> </script>
<script type="text/javascript">
  var x = $('p').html();
  document.write(x);
</script>
</head>

<body>
  <p class="first">Hello World  </p>
</body>

</html>

Upvotes: 1

Views: 2308

Answers (3)

noob
noob

Reputation: 9202

I can't see anything what isn't working (example)

maybe you should write

jQuery(document).ready(function($){
    //your javascript code
})

but if it doesn't work with that either I should remind you that document.write normally replaces the content

Upvotes: 0

Paul
Paul

Reputation: 141839

You are running your script before The <p class="first">Hello World</p> is reached in your HTML. Put your script in the body instead just after the <p> tag:

<html>
    <head>
        <script type="text/javascript" src="js/jquery.js"> </script>
    </head>
    <body> 
        <p class="first">Hello World</p>
        <script type="text/javascript">
            var x = $('p').html();

            document.write(x);
         </script>
    </body>
</html>

You can also use jQuery's ready function like some others have said, but that's an inefficient solution since you already know at which point in the document the <p> tag is loaded. It's much better to run your script as soon as it's loaded then to wait for the whole document to load using $.ready.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382666

Wrap your code in $.ready handler:

<script type="text/javascript">

$(function(){
  var x = $('p').html();
  document.write(x);
});

</script>

The ready handler fires after DOM has loaded and parsed meaning only then you can maipulate tags (or DOM).

Upvotes: 3

Related Questions