Reputation: 97
I am currently dabbling with Jquery/Javascript and manipulating a DOM Tree/elements.
I have a few parent elements which are LI's and the children are nested inside using a UL as can be seen in the html code below.
<div class="TheList">
<ul>
<li class="theTop">Parent
<ul>
Child 1
</ul>
<ul>
Child #2
</ul>
</li>
<li>Parent 2</li>
<li>Parent 3
<ul>
Child 1
</ul>
</li>
</ul>
</div>
How would one go about highlighting/selecting each element individually? What I mean is when I click one of the elements e.g Child 1 it would become the selected and then place something there to show it's selected i.e border:dashed
The overall aim was to manipulate the data so that when I select one of the elements, again, lets say Child 1 I could have code on a button that will get the selected element and add another child to it's family or under the parent node.
I understand my question may sound vague so I have attached an image with a (very shabbily made) mock-up of what I mean. If there are any other pieces of info needed just let me know.
Upvotes: 1
Views: 74
Reputation: 403
Not sure if I understand the question, but does this solve your problem?
Start by giving each ul
tag you want to be selectable a class.
$('.selectable').click(function() {
$(this).toggleClass('selected');
});
$('button').click(function() {
$('.selected').parent().append('<ul></ul>');
});
then you could have css for the selected
class
.selected {
border: dashed 1px black;
}
like this:
$('.selectable').click(function() {
$(this).toggleClass('selected');
});
$('button').click(function() {
$('.selected').parent().append('<ul>a</ul>');
});
.selectable {
border: solid 1px red;
}
.selected {
border: dashed 1px black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<ul class="selectable">
1
</ul>
<ul class="selectable">
2
</ul>
</li>
<li>
<ul class="selectable">
3
</ul>
</li>
</ul>
<button>Add Child</button>
Upvotes: 2