Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to color a treeview node in javascript

Tags:

javascript

dom

i have a treeview and a texbox that allows a user to search for nodes inside the treeview.

i already wrote the JS function that determines if a node exists in the treeview.
what i want is to color the node that the user have searched for. how can i do this??

like image 330
hero Avatar asked May 22 '26 17:05

hero


1 Answers

Use CSS and change the className in Javascript. So say your nodes are divs. When you find the node, in Javascript, you would do something like:

divFoundNode.className = "selected";

Then make sure your CSS has a selected class with a background color set. That would look something like this:

.selected {background-color:red;} /* whatever your selected color is here */

If you don't want to use CSS, you can change the color of the node directly by doing something like this:

divFoundNode.style.backgroundColor = "red";

Now, you'll probably also need to turn off the selection of whatever other node was previously selected first. To do that, you've got a couple of options. You can run through all nodes and remove the color before setting the selected one (like above) or you can store a variable in your Javascript with the last selected div and just target that one. So you'd do something like this:

var divLastFoundNode; //global variable

function treeView_SelectNode(divFoundNode)
{
     divLastFoundNode.className = "";
     divFoundNode.className = "selected";
     divLastFoundNode = divFoundNode;
}

JQuery would make this quite a bit easier. You can select lots of nodes and perform operations on all of them at once. For instance:

$("div.node").removeClass("selected");
$(divFoundNode).addClass("selected");
like image 147
sohtimsso1970 Avatar answered May 25 '26 07:05

sohtimsso1970