Search code examples
javascriptjqueryclone

Selecting element to copy using jQuery Clone


I have a guide where each chapter is located in a separate LI of a UL. I am trying to use the jQuery Clone function to search through the parent UL that contains all of these 'chapter' LIs, and return those chapters that contain specific text.

Right now, I'm getting odd results, likely because it's copying elements at their smallest child, rather than just the entire div.

Also, each of these chapter LIs should only be returned once.

  • makeIntoSldieshowUL - UL that contains all 'chapters'
  • slideShowSlide - class name for each 'chapter'
  • searchResultsArea - Div in which to append 'chapters' that contain text

So far I have:

$("#makeIntoSlideshowUL").find(".slideShowSlide:contains('" + $(this).val() + "')").clone().appendTo("#searchResultsArea");

To give you an idea of the content I'm looking to clone, here is a brief sample

<ul id="makeIntoSlideshowUL">
<li  class="slideShowSlide" id="0">
    <div class="topicTitle">Cardholder responsibilities</div>
    <p>Cardholders are responsible for ensuring proper use of the card. If your division or department has approved you for a Pro-Card, you must use the card responsibly in accordance with the following requirements:</p>
    <ul>
        <li>Purchase items for UCSC business use only</li>
        <li>Never lend or share your Pro-Card</li>
        <li>Purchase only allowable goods and services</li>
    </ul>
</li>
<li class="slideShowSlide" id="1">
    <div class="topicTitle"><strong>Restricted and Unallowable Pro-Card Purchases</strong></div>
    <p>Some types of purchases are restricted are not allowed with the Pro-Card.  Disputes with suppliers are initially handled by the Cardholder if, for example, they don't recognize a transaction on their statement, or the amount doesn't match their receipt. The Cardholder is responsible for contacting the supplier immediately to try to resolve the matter.</p>
</li>


Solution

  • Use jQuery's .children() method instead of .find() since it sounds like the .slideShowSlide elements are immediate children.

    $("#makeIntoSlideshowUL").children(".slideShowSlide:contains('" + $(this).val() + "')").clone().appendTo("#searchResultsArea");
    

    Or you could use the > child selector instead.

    $("#makeIntoSlideshowUL > .slideShowSlide:contains('" + $(this).val() + "')").clone().appendTo("#searchResultsArea");
    

    EDIT: At one point, you seem to refer to the chapters as divs. If they're a child of the <li> elements, you'll likely need something like:

    $("#makeIntoSlideshowUL > li > .slideShowSlide:contains('"...