Tuesday, 27 August 2013

Shorter way to write this?

Shorter way to write this?

I'm currently working on a HTML/CSS/jQuery-based interactive tree diagram,
and I've come across a minor detail, but still something I'd like to ask.
HTML structure:
<ul id="node_81">
<li>
<p>Node Label</p>
<ul id="node_120">
<li>
<p data-node="120">Child Node Label</p>
<ul id="node_123">
<li id="node_456">
<p data-node="456">GrandChild Node Label</p>
</li>
<li id="node_457">
<p data-node="45">GrandChild Node Label</p>
</li>
</ul>
</li>
<li>
<p>Child Node Label</p>
</li>
</ul>
</li>
</ul>
(All id's etc. chosen at random, just so you get the structure)
Now, I have .click events bound to every <p> element (which provides the
visual representation of the node), and when a node is clicked, I change
the appearance of that node (thus, the appearance of the <p>).
This is a snippet of the click function:
$(".tree-js p").removeClass("nodeSelected");
if(main.selectedNode > -1) {
if($("#node_"+ main.selectedNode).is("p")) {
$("#node_"+ main.selectedNode).addClass("nodeSelected");
} else {
$("#node_"+
main.selectedNode).prev("p").addClass("nodeSelected");
}
As you can see here and in the HTML structure, if the tree node is at the
end of a branch (here: the GrandChildren nodes), its ID attribute is in
the <p> element, not the <ul> element, because that <ul> element is only
present when a node has children.
So it's working, no problem there, but I just hate to use an if-block like
that. I have a feeling that I can probably write that in 1 line of jQuery
but I just can't grasp it at the moment.
What it boils down to: select element_with_certain_id, add class
"nodeSelected" to node's <p> element, unless this element is <p>, then add
class to self
So yeah, no big problems, just curious whether this can be shortened.
EDIT If-block works now. Still looking to shorten it.

No comments:

Post a Comment