Search code examples
jqueryarraysinnerhtml

How can I have an array of the html content of a JQuery element?


I want to have the inner html of a series of elements. This is what I tried:

slides = $("#slides p");

It gives me a series of objects, but I want the raw html of each! I tried $("#slides p").html() but it gives the first paragraph.


Solution

  • You can get the collection, convert it to an array with .toArray and then use .map to iterate over it and get the inner HTML of each item.

    const ptext = $('#slides p').toArray().map(p => p.innerHTML);
    console.log(ptext);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="slides">
      <p>Peter</p>
      <p>Ray</p>
      <p>Egon</p>
      <p>Winston</p>
    </div>