Zelí
Zelí

Reputation: 121

Js find specific div with data attribute

Hi im working on javascript chat and i want to append data to conversation that it belongs to i have function to create new window and im setting a data attribute to each chat div

newWindow: function(name, id) {               
            if(!pushChatToArray(removeWhiteSpace(name))) return;                
            var div = htmlStructure(removeWhiteSpace(name));                
            setName(div, name);                
            setDataAttribute(div,"open","active");                
            setDataAttribute(div, "id", id);                
            $("body").append(div);                
            setCoordinates(div);
        },

im creating new windows like this

chatbox.newWindow("USERNAME", "28");

all i want is select the specific chat div by the data atribute id

this code im using when im writing somebody that i have focused,so i can get the id by selecting the div like this :

var id = $(this).closest(".chat").data("id");

but i want to find chat with specific id like this

var chatid = $("body").find(".chat[data-id=1]");

Thank you for help

Upvotes: 0

Views: 111

Answers (2)

fanfan1609
fanfan1609

Reputation: 179

I think you can use as below

var chatid = $(".chat").find("[data-id='" + current + "']");

Also, I find more tip in jQuery how to find an element based on a data-attribute value?

You should use attr("data-id") than data("id")

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

Try this:

var chatid = $('.chat').filter(function () {
    return $(this).data('id') == 1;
});

Upvotes: 1

Related Questions