Hello! I do a test, google it, everything seems ok, but hr does not appear ... (((Tell me what I'm doing wrong: add hr after h2 using .insertBefore ()

$(document).ready(function() { $("h3").addClass("sel"); $("h3").insertBefore("<hr/>"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2 id="id2">A</h2> <h3 id="id3">B</h3> <h4 id="id4">C</h4> 

I get to the element, but hr is not added ...

    1 answer 1

    If you look at the help on the insertBefore function, you can see what exactly this function does:

    Insert every element before the target.


    Inserts each element from the set in front of the elements passed in the parameter

    In this case, <hr/> is passed as the target — thus, when the function is called, such an element is created, h3 is added in front of it, but since the created element is not added anywhere, it is not shown.

    You can use the before method to fix it.

     $(document).ready(function() { $("h3").addClass("sel"); $("h3").before("<hr/>"); }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2 id="id2">A</h2> <h3 id="id3">B</h3> <h4 id="id4">C</h4> 

    Or swap the parameters:

     $(document).ready(function() { $("h3").addClass("sel"); $("<hr/>").insertBefore("h3"); }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2 id="id2">A</h2> <h3 id="id3">B</h3> <h4 id="id4">C</h4> 

    • changed places and everything works! Thanks for the help) - ultimatum