Search code examples
jqueryeachalternate

Alternating two jQuery objects


I am trying to extract an old FAQ system from my old site and recode it into a <dl>.

This is my jQuery code so far:

$accordion = $('.accordion');
$headers = $accordion.find('h3.trigger-h3-accordion a');
$content = $accordion.find('div.toggle-accordion-large');

out = "<dl>\n";
$headers.each(function(k,v) {
    out += "<dt>" + $(this).text() + "</dt>\n";
    out += "<dd>" + $content[k].html() + "</dd>\n";
    // I also tried $content.k.html() and $content{k}.html()
    // and .text() on all of those options
});
out += "</dl>\n";
console.log(out);

I get the error: TypeError: $content[k].html is not a function

On line: out += "<dd>" + $content[k].html() + "</dd>\n";

<div class="accordion">
    <div class="trigger-accordion-large trigger-accordion-active">
        <h3 class="trigger-h3-accordion"><a href="#" onclick="return stopAccordionRefresh();">Header Text</a></h3>
    </div>
    <div style="display: block;" class="toggle-accordion-large">
        <div class="block-large">
            <div class="body-content-textarea">
                <p>Content Text.</p>
            </div>
        </div>
    </div>
</div>

How can I output the content of each $content object within the loop to create the valid <dl><dt><dd> I am after?


Solution

  • Try this:

    $($content[k]).html();
    

    Because, .html() only work with jQuery object, according to your error it seems $content[k] is not an jQuery object, may be an element.

    So, wrapping it within $() will make it a jQuery object and then you can able to use any jQuery method to it.

    If $content[k] is an element then you can use:

    $content[k].innerHTML = 'your_all_html';