-2

I'm new to Javascript. With the code below, I'm interested in displaying three values. The first problem that I've encountered is the document.write won't work. What am I typing in wrong? The other problem is that I'd like to display the text that the first_div contains on the screen in the browser window. I believe that all of the divs in the first_div will show the text 'value.' How do I get this to display?

<html>
<head>
</head>
<body>
<div class= 'first_div'>
  <p>Content</p>
  <div class='comment'></div>
  <div class='comment'></div>
  <div id='pagination'></div>
</div>




  <script type='text/javascript'>
    document.write("Hello");
    jQuery(function() {
      $('#pagination').addClass('comment');
      $('.first_div.comment').text('value');
      $(document.body).append('hello');

  });



 </script>

</body>
</html>
J_Dawg
  • 17
  • 1
  • 1
    See [Why is document.write considered a “bad practice”?](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice). If you want to select all `div.comment` elements that are inside `div.first_div`, you'll need a space between the two, i.e. `$('.first_div .comment')`. See [jQuery Descendant Selector](https://api.jquery.com/descendant-selector/). Here's a [working example](https://jsfiddle.net/5148usom/). – showdev Jun 08 '16 at 21:42
  • Thanks showdev, that was quite helpful. – J_Dawg Jun 08 '16 at 22:07

1 Answers1

1

Currently .first_div.comment is looking for an element with both classes. You want an element .first_div with a child element .comment. To do this, use a space to select all descendants (not just children) of what was prior to the space.

Your line of code would then look like this: $('.first_div .comment').text('value');

Learn more about CSS selectors here (this will help you for other similar problems): https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors#Information_Selectors_based_on_relationships

Pluto
  • 2,525
  • 22
  • 31