i have the following html :-
<span id="event">
<ul>
<li>Activities
<ul>
<li>Physical1
<ul>
<li>Cricket
<ul><li>One Day</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</span>
<div id="activity"></div>
i want to set the click event on every li using jquery click function
it works perfect but i want to set this li text in #activity
div
here is what i have tried:
$("#event ul li").live("click", function(event){
event.stopPropagation();
alert($(this).text());
$("#activity").append($(this).text());
return false;
});
/
now problem in them when i am click on li its append all the li text in div, i want only clicked li text.
when click on li
there text append in div
tag eg:- click on Cricket then cricket append in div when click on One Day append on Div...
how do i do this? thanks.
i have the following html :-
<span id="event">
<ul>
<li>Activities
<ul>
<li>Physical1
<ul>
<li>Cricket
<ul><li>One Day</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</span>
<div id="activity"></div>
i want to set the click event on every li using jquery click function
it works perfect but i want to set this li text in #activity
div
here is what i have tried:
$("#event ul li").live("click", function(event){
event.stopPropagation();
alert($(this).text());
$("#activity").append($(this).text());
return false;
});
http://jsfiddle/Va5E4/7/
now problem in them when i am click on li its append all the li text in div, i want only clicked li text.
when click on li
there text append in div
tag eg:- click on Cricket then cricket append in div when click on One Day append on Div...
how do i do this? thanks.
Share Improve this question edited Apr 29, 2013 at 12:49 jack lanza asked Apr 29, 2013 at 12:40 jack lanzajack lanza 2993 silver badges18 bronze badges 1- Add your javascript to your question too, not just in JSFiddle – Michiel Commented Apr 29, 2013 at 12:44
3 Answers
Reset to default 10You can grab the first childNode
of the clicked li
and append that:
$("#activity").append(this.childNodes[0].nodeValue);
Here's a fiddle
Here is an alternative using jquery methods
What it does is to make a clone of the clicked node, then remove all the child nodes. What is left is just the the clicked node, so we get only it's text.
$("#event li").on("click", function (event) {
event.stopPropagation();
$("#activity").append($(this).clone().children().remove().end().text());
return false;
});
On jsfiddle
Please have a look on http://jsfiddle/Va5E4/12/
<div id="event">
<ul><li>Activities
<ul> <li>Physical1
<ul> <li>Cricket
<ul><li>OneDay </li></ul>
</li> </ul>
</li> </ul>
</li></ul>
</div>
<div id="activity"></div>
$("#event ul li").on("click", function(event){
event.stopPropagation();
var html = $(this).html()
var word = html.substr(0, html.indexOf(" "));
$("#activity").append(word);
return false;
});
Note: This will work for if you have 'single string' as 'value' of 'li' otherwise it won't work.