Enissay
Enissay

Reputation: 4953

Wrap elements with jQuery

I'm using AJAX with jQuery to get some html content and here's the success function:

function successFn(data) {

    var keyWord = $("#input").val();

    // convert string html to object
    var anchors = $('<div/>').html(data).contents();

    // add data-keyword to all results
    anchors.each( function (i) {
        $(this).attr('data-keyword', keyWord);
        $(this).wrap('<div class="xXx"></div>');
    });

    // print results
    $("#results").html(anchors);
}

The data contains a a list of anchors:

<a href="link">...children...</a>
<a href="link">...children...</a>
<a href="link">...children...</a>
<a href="link">...children...</a>

So i'm trying to add an attribute to these links, which is working Then I wrap each anchor with a div, which is not working.

Why isn't it wrapping?

Upvotes: 0

Views: 76

Answers (1)

epascarello
epascarello

Reputation: 207491

The problem is you are only adding the anchor elements, you are not including the content that you wrapped.

function successFn(data) {

    var keyWord = $("#input").val();

    // convert string html to object
    var wrapper = $('<div/>').html(data);
    var anchors = wrapper.contents();

    // add data-keyword to all results
    anchors.each( function (i) {
        $(this).attr('data-keyword', keyWord);
        $(this).wrap('<div class="xXx"></div>');
    });

    // print results
    $("#results").empty().append(wrapper.contents());
}

Upvotes: 2

Related Questions