How do I get the id of the selected node in jsTree? - javascript

How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert('test');
var tree = $.tree.reference("#basic_html");
selectedNodeId = xxxxxxxxx; //insert instruction to get id here
tree.create({ data : "New Node Name" }, selectedNodeId);
}

Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected function returns an array of selected list items. If you do .attr on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.

Nodes in jsTree are essentially wrapped list items. This will get you a reference to the first one.
var n = $.tree.focused().get_node('li:eq(0)')
You can replace $.tree.focused() if you have a reference to the tree.
To get the id, take the first matched element
if (n.length)
id = n[0].id
or you can use the jQuery attr function, which works on the first element in the set
id = n.attr('id');

In jstree version 3.1.1, you can get it directly from get_selected:
$("#<your tree container's id>").jstree("get_selected")

In the most recent version of jsTree (checked at 3.3.3), you can do this to get an array of IDs:
var ids = $('#tree').jstree('get_selected');
This will return, for example, ["selected_id1", "selected_id2", "selected_id3"]. If you want to get the selected nodes (not IDs), you can do this:
var nodes = $('#tree').jstree('get_selected', true);
The current docs contain more information.

$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});

I was having problems getting the selected ids from a tree with MULTIPLE selections. This is the way I got them:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});

In my case, the data call doesnt work.
I succeed in accessing my node data by using attr function.
$("#tree").jstree("get_selected").attr("my-data-name");

to get all selected ids use the below code
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
now you have all the selected id's in the "selectedData" variable

<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>

Just use
var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;
where #FaqTreeView is the id of your div that contains the jstree.

In some cases and/or jstree versions this solution doesn't work.
$('#tree').jstree('get_selected').attr('id');
Instead of defined "id" I get nothing.
What did the trick for me is:
$("#tree").jstree("get_selected").toString();

These are all old answers for old versions. As of version 3.3.3 this will work to get all attributes of the selected node.
$('#jstree').jstree().get_selected(true)[0]
If you then want the id then add .id at the end. You can look at all the other attributes in web developer tools if you copy the above code.

You can use the following code
var nodes = $("#jstree_demo_div").jstree(true).get_selected("full", true);//List of selected node
nodes[0].id//Which will give id of 1st object from array

With the latest version of jsTree, you can do it as follows:
var checked_ids = [];
$('#your-tree-id').jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));

Related

How can I get nth table column value in Javascript

How can I get nth table column value? Ie. I would like to get 2nd column value.
The first one I get in this way - it works fine, but the nth(2) does not work:
$('body').on('click', '.confirmation1', function(e) {
e.preventDefault();
var produktNazwa = $(this).parents("tr").find("td").first().html();
var produktWaga = $(this).parents("tr").find("td").nth(2).html();
console.log(produktNazwa, produktWaga);
});
Any hints on this please? Thanks.
There is no .nth() in jQuery. Instead you can try with .eq():
Reduce the set of matched elements to the one at the specified index.
var produktWaga = $(this).parents("tr").find("td").eq(2).html();
OR: You can include :eq() as part of the selector:
var produktWaga = $(this).parents("tr").find("td:eq(2)").html();
I don't recall having nth function in jQuery. I might be mistaken, but not that I know of. What you probably want is eq()
var produktWaga = $(this).parents("tr").find("td").eq(2).html();

Protractor - get child element of an element?

I am trying to access child element of an ng-repeat element but I am having troubles doing that.
I have searched around about the problem and the solutions that I have found did not work for me. One of those solutions was to do something like this:
var parent = element(by.repeater(''));
var child = parent.element(by.....);
When I try the child line I cant see the element function on the parent element..
http://prikachi.com/images/11/8338011u.png
If you see the screenshot above you will see the structure of the code of the page that I am trying to test.
I need to access the alt attribute of the image of the avatar and get its value (thats the Username of the User).
One thing that came to my mind is to use .getInnerHTML() on the ng-repeat row which will return a string with all that code. From there I can find the alt attribute and its value with string manipulation but this seems too brute and I am sure that there has to be a better way.
Simply I want to be able to get row 4 from the repeater and get the Username of the user at row 4, that's all I wanna do actually.
Try this,
var parent = element(by.repeater('f in feed'));
var child = parent.all(by.xpath('//img[#alt="Pundeep"]')).first()
(or)
var parent = element(by.repeater('f in feed'));
var child = parent.all(by.xpath('//img[#alt="Pundeep"]')).get(0)
You can get it directly using element.all() and get() locator in protractor. Here's how -
var child = element.all(by.repeater('parent_locator')).get(3); //gets 4th element in repeater. Its a 0 based index.
child.getAttribute('alt').then(function(user){
var username = user; //username contains the alt text
});
Hope this helps.
In Protractor element documentation it gives an example like this to find child elements, which is same as chaining element find:
// Chain 2 element calls.
let child = element(by.css('.parent')).
$('.child');
expect(child.getText()).toBe('Child text\n555-123-4567');
// Chain 3 element calls.
let triple = element(by.css('.parent')).
$('.child').
element(by.binding('person.phone'));
expect(triple.getText()).toBe('555-123-4567');
// Or using the shortcut $() notation instead of element(by.css()):
// Chain 2 element calls.
let child = $('.parent').$('.child');
expect(child.getText()).toBe('Child text\n555-123-4567');
// Chain 3 element calls.
let triple = $('.parent').$('.child').
element(by.binding('person.phone'));
expect(triple.getText()).toBe('555-123-4567');
https://www.protractortest.org/#/api?view=ElementFinder.prototype.$
this example could help :
return element(by.css('select.custom-select:nth-child(1) option[value="12"]'));
you can use nth-child() selector to access to a child element.
In my example i used a plugin with 2 select with same classes and i wanted to click on a defined option in the select 1, and a second in the select 2.

jQuery: easier way to use .clone() than described below?

If you execute in the console on this page
var cloned = $(".question").clone(true);
$(".question").addClass("first");
var clonedStr = cloned[0].outerHTML || new XMLSerializer().serializeToString(cloned[0]);
$(".question").after(clonedStr);
you will clone the question (there will be two questions on the page, but the first one will be with the .first class). That's what is needed.
Is there any simpler way to do this with jQuery? I'm confused of the third string in the code above and believe it could be simpler. Any ideas?
Thank you.
If you don't use the HTML as string, then don't get it. Just use the jQuery object:
var cloned = $(".question").clone(true);
$(".question").addClass("first").after(cloned);
Also, you can do it one line:
$(".question").after($(".question").clone(true)).first().addClass("first");
You could use insertAfter to insert the cloned element after changing the class. You don't need to convert the element in the jQuery object to a string, you can use that object within the function itself:
var $question = $('.question');
var $cloned = $question.clone(true).insertAfter($question);
$question.addClass('first');

How to access first or specific object from json data

I have a json file with below mentioned format
mydata.json
{
"nodes":{
"Aidan":{"color":"green", "shape":"dot", "alpha":1, "id" : "aidan"},
"Sofia":{"color":"green", "shape":"dot", "alpha":1},
"Liam":{"color":"GoldenRod", "shape":"dot", "alpha":1}
},
"edges":{
"Quinn":{
"Liam":{"length":2.5,"weight":2},
"Audrey":{"length":2.5,"weight":2},
"Noah":{"length":2.5,"weight":2},
"Claire":{"length":2.5,"weight":2}
},
"Liam":{
"Sofia":{"length":2.5,"weight":2},
"Ethan":{"length":2.5,"weight":2},
"Amelia":{"length":2.5,"weight":2}
}
}
}
I will be reading above file data using jquery as mentioned below
var data = $.getJSON("data/mydata.json",function(data){
var nodes = data.nodes;
var edges = data.edges;
//i want to access first element or between element.
//like var edge = edges.get(0) or nodes.get("aidan")
})
I want to access first element or between element with the index or by name property of object. like var edge = edges.get(0) or nodes.get("aidan").
Thanks
There are several ways of doing it
Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn
A little warning on the first one, Object in JS are unordered so it may break, thus browser tends to keep the insertion order.
hope it helped
Try this code
nodes['aidan']
edges['Quinn']
Either the before mentioned code
nodes['aidan']
or
nodes.aidan
should work equally fine.
Prepared a fiddle for you. You can check there.

How do I get multiple jquery attr values?

My code:
http://codepen.io/vincentccw/pen/ecJDG
Basically what I want to get are all the data attribute values from the attr call data-designer
There are suppose to be 4 of them but I can only get the first one using:
var dsad = $('ul').attr("data-designer");
How do I fix this?
You can use each() to interact with each element individually:
$('ul').each(function(){
console.log($(this).data('designer'));
});
Or you can use map() to create an array of all the values which you can deal with separately:
var designers = $('ul').map(function() {
return $(this).data('designed');
});
console.log(designers);
Note, I used data to get the data-* attributes as this is quicker than accessing the attributes of the DOM element directly.
$('ul').each(function(){
console.log($(this).attr('data-designer'))
//you can add to an array also
});
You can use map() to project the attribute values into an array:
var designers = $("ul").map(function() {
return $(this).attr("data-designer");
}).get();
You need to use .each()
$('ul').each(function(){
console.log($(this).attr("data-designer"));
});
Codepen Demo
$('ul').attr("data-designer") just got the attribute for the first ul element. If to get all uls with "data-designer" attribute, try this:
$('ul[data-designer]').each(function(){
console.log($(this).attr("data-designer"));
});

Categories

Resources