Robert Dickey
Robert Dickey

Reputation: 834

.attr() get <img> content

I have a application that is using Jquery UI. to create a drag and drop sortable picture list. These pictures are inserted in to the <li> of a <ul>. Through the below code, I am able to loop through, receiving the contents of each listed li, but not the contents of the <img> tag.

$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
});

var LISTOBJ = {
    saveList: function() {
        var listCSV = "";
        $( "#sortable li" ).each(function() {
            if (listCSV === "") {
                listCSV = $(this).text();
            } else {
                listCSV += "," + $(this).text();
            }
            $("#output").text(listCSV);
            $("#hiddenListInput").val(listCSV);
            //$("#listsaveform").submit();
        });
    }
}

My question is - Why can I see the contents of the <li>, but not of the img tag inside it? I believe the answer lies somewhere in adding a .attr() to the .each, but I can't seem to figure it out.

Does anyone know what I am missing, or if I am even on the right track?

Upvotes: 0

Views: 450

Answers (1)

Luca Rainone
Luca Rainone

Reputation: 16468

You should use html() instead of text() in order to get all <img> tag

        if (listCSV === "") {
            listCSV = $(this).html();
        } else {
            listCSV += "," + $(this).html();
        }

or if you want only the src attribute

        if (listCSV === "") {
            listCSV = $(this).find('img').attr('src');
        } else {
            listCSV += "," + $(this).find('img').attr('src');
        }

Upvotes: 1

Related Questions