JQuery: append item before element's HTML

I need to append some HTML before the existing HTML of an element. I have tried:

$("p").each(function(index){
  $(this).prepend('HELLO! ');
});

But this places it before <p>.

I've also tried:

$(this).html().prepend('HELLO! ');

The result I need to get would look like:

<p>HELLO! This is existing text</p>

Would anyone know the best way to do this?

Answers 1

  • $("p").each(function(index){
      $(this).before('HELLO! ');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>paragraph</p>
    
    <p>paragraph</p>

    use .before()

    Description: Insert content, specified by the parameter, before each element in the set of matched elements.


Related Articles