Nikil Nikil - 1 month ago 6
Javascript Question

Knockout js get specific DOM element ID

i am using the knockout js in my web app,i am getting data from database and binding data using knockout js with checkbox its working, when i checked the checkbox i am getting all related data to it,but i need element ID of all the div when i checked the particular checkbox, is it possible or not ,how i can achieve this need help

<div data-bind="foreach:items">
<ul data-role="listview">
<li>
<span id="txtuserID" data-bind="text:userId" style="display:none"></span>
<span id="txtuserName" style="margin-top: 10px;font-size: 22px;font- weight: bold;padding-left:0px;" data-bind="text:username"></span>
<div data-bind="attr:image" class="Image">
<div id="img1"><img src=1.png /><div>
<div id="img2"><img src=2.png /><div>
<div id="img3"><img src=3.png /><div>
</div>
<input id="chkID" type="checkbox" data-bind="value:userId(), checked: $root.addItemTitle, click: $root.toggle" /></li>
<ul>
</div>

<!-- language: lang-js -->

function UserDetails() {
var self = this;

function(userId username) {
var self = this;
self.userId = userId;
self.username = ko.observable(username)
self.Image=ko.computed(function() {
return this.Image() + " " + this.Imagetype();
}, this);
}

}
self.addItemTitle = ko.observable();
//Check Box Selected
self.toggleAssociation = function(item, event) {
if (item.Selected() === true) console.log("dissociate item " + item.userId());
else console.log("associate item " + item.UserID() + " " + "UserName " + item.UserName(), "you clicked " + event.target.id);
/// here i am getting userID,Username and checkbox element id=chkid, is it possible to get userName elementID
item.Selected(!(item.Selected()));
return true;
};
}

Answer

To navigate through the HTML domain you can use these 2 JS methods

event.target.parentElement //Returns the parent object
event.target.children //Returns Children

so you can do this:

var li = event.target.parentElement;

with that you have acess to all your objects in relation to the checkbox. To get the div children you can do this:

var liChild = li.children;

that returns an array of all the elements inside the div.

to get all the ids you can do this:

function getIDs(array) {
    var output = [];
    for (var i = 0; i < array.length; i++) {
        output[i] = array[i].id;
    }
    return output;
}

and then

var ids = getIDs(liChild);

if you want to get the div you can do this

var li = event.target.parentElement;
var ul = li.parentElement;
var div = ul.parentElement;
var divChild = div.children;
var divIDs = getIDs(divChild);
Comments