Just started to learn jQuery, the first program from the book, and it does not work.

<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style type="text/css"> .stripped { background-color: yellow; } .table { border: 1px solid black; border-collapse: collapse; } .table tr { border: 1px solid black; } </style> <script type="text/javascript"> $("table tr:nth-child(even)").addClass("stripped"); </script> </head> <body> <table class="table"> <tr><td>текст 1</td></tr> <tr><td>текст 2</td></tr> <tr><td>текст 3</td></tr> <tr><td>текст 4</td></tr> <tr><td>текст 5</td></tr> </table> </body> </html> 

What's wrong with the code?

    2 answers 2

    Did you, by any chance, remember to connect the jquery library? Check, please. Since in the example it is not connected. And in this case, the result is predicted;)


     чего сейчас не хватает? 

    And now you call the function $ ("table tr: nth-child (even)"). AddClass ("stripped"); before you have a DOM document. That is, you call before the table appears on the page and the javascript does not find anything.

     $(document).ready(function(){ // вызывается после подготовки DOM страницы $("table tr:nth-child(even)").addClass("stripped"); }) 
    • Oh, thank you very much, I forgot that this is not just javascript, but a library is needed - Heidel
    • You're welcome. For this we are here :) - iKuzko
    • Hmmm, I added the line <script src = " ajax.googleapis.com/ajax/libs/jquery/1.7.2/… ... > to the head . It should be enough for jquery to work, but it doesn't work. What is missing now? - Heidel
    • one
      Added in response. You need to either use $ (document) .ready (function () {...}) or add a javascript at the end of the page (the latter is less preferable). - iKuzko
    • URRRRA !!! It worked !!! - Heidel

    Pseudo-class: nth-child is available in regular CSS

    • That's right, but here they are trying to learn how to use jquery and make samples of various kinds (for example, all the even rows of the table) are a good start. They even indicated that this is the first lesson from the book. - iKuzko
    • I know that the pseudo-class: nth-child is available in css, but I want to use jQuery. - Heidel