Unable to get <li> ID - javascript

I'm using this code to get ID of li, but I am able to get only ul ID. Below is the code. Can anyone help me.
$("#trash ul li").click(function(event) {
var $item = $(this),
$target = $(event.target);
//recycleImage($item);
alert($(this).attr('id'));
{
alert($(this).attr('id'));
});

var $item = $(this),
Remove comma from the end of the above line

try this
html
<div id='trash'>
<ul id='ul'>
<li id="li">
list1
</li>
</ul>
</div>
javascript
$("#trash ul li").click(function( event ) {
var $item = $( this )
$target = $( event.target );
alert($(this).attr('id'));
{
alert($(this).attr('id'));
}
});
fiddle

Related

Draggable LI's connected by SVG-Lines using JavaScript

following is the image of till now done want to connect those parent and child ul li
hi,
will appreciate you help.
I want to create a extendable list, in wich the children-li's are connected to their parant-li's trough a SVG-Line. The li-Elements should also be draggable. Here an example, which is close to my vision.
Here my working code without the SVG-Lines and undraggable li's.
var chidID = 0;
$('body').on('click', '.ul-appending', function() {
var levelID = $(this).attr('data-levelnumber');
var parentID = $(this).attr('data-parentNumber');
createNode(levelID,parentID,chidID,this);
//getParent(this);
});
function createNode(levelID,parentID,chidID,elem){
console.log(levelID,parentID,chidID);
levelID++;
parentID++;
$(elem).parent().append(
$('<ul>').addClass('newul')
.append(
$('<li>')
.append(
$('<button>').addClass('ul-appending').text("Add UL").addClass('marginBottomUl').attr('data-parentNumber',parentID).attr('data-levelnumber',levelID)
)
)
);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul>
<li><button class="ul-appending" data-parentNumber='0' data-levelnumber='0'>Main Parent</button> </li>
</ul>
</div>
Here's a working example for your vision. Not everything works as you want it to, but I think with that, you can go on and solve your issue.
Here the snippet:
$(document).ready(function(){
var chidID = 1;
$('body').on('click', '.ul-appending', function() {
var levelID = $(this).attr('data-levelnumber');
var parentID = $(this).attr('data-parentNumber');
chidID++;
createNode(levelID,parentID,chidID,this);
//getParent(this);
});
function createNode(levelID,parentID,chidID,elem){
levelID++;
parentID++;
var btnNew = $('<button>').addClass('ul-appending').text("Add UL").addClass('marginBottomUl').attr('data-parentNumber',parentID).attr('data-levelnumber',levelID).attr("id", chidID);
$(elem).parent().append(
$('<ul>').addClass('newul')
.append(
$('<li>')
.append(
btnNew
)
)
);
var mySVG = $('body').connectSVG();
mySVG.drawLine({
left_node:'#'+$(elem).prop("id"),
right_node:'#'+chidID,
horizantal_gap:10,
error:true,
width:1
});
$( '#'+$(elem).prop("id") ).draggable({
cancel: false,
drag: function(event, ui){
mySVG.redrawLines();
}
});
$( '#'+chidID ).draggable({
cancel: false,
drag: function(event, ui){
mySVG.redrawLines();
}
});
}
});
button {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://www.jqueryscript.net/demo/jQuery-Plugin-To-Connect-Two-Html-Elements-with-A-Line/required/script/jquery.svg.min.js"></script>
<script src="http://www.jqueryscript.net/demo/jQuery-Plugin-To-Connect-Two-Html-Elements-with-A-Line/required/script/jquery.connectingLine.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<div>
<ul>
<li><button id="1" class="ul-appending" data-parentNumber='0' data-levelnumber='0'>Main Parent</button>
</li>
</ul>
</div>

jQuery if and $(this) confusion

Something that has been bugging me for a while.
JavaScript
$('.video-tab-container ul li a').click(function(e) {
var thisClass = $(this).attr('class');
console.log(thisClass);
if ( $('.video-container .video').is('.' + thisClass) ) {
$(this).addClass('test');
}
e.preventDefault();
});
HTML
<div class="video-tab-container clearfix">
<ul>
<li><a class="chinese" href="#">Chinese</a></li>
<li><a class="thai" href="#">Thai</a></li>
<li><a class="english" href="#">English</a></li>
</ul>
</div>
<div class="video-container">
<div class="video chinese"></div>
<div class="video thai"></div>
<div class="video english"></div>
</div>
Within the if statement, how do I make $(this) the element within the if statement? So, if the statement is true, the class test is added to the .video with the corresponding class? Maybe I am doing this all wrong.
You need to use:
$(this).closest('.video-tab-container').next()
.find('.video.' + thisClass).addClass('test')
.siblings('.video').removeClass('test');
instead of:
$(this).addClass('test');
because currently $(this) is treated as your clicked anchor.
Fiddle Demo
I think replacing your if statement with this:
$('.video-container .video.' + thisClass).addClass('test');
will do what you're trying to do. Like the commenters above said, the "if" statement doesn't change what "this" refers to.
The reference to this isn't going to change just because it's within an if statement.
If you want the reference to this to change the statement needs to be written like this:
$('.video-tab-container ul li a').click(function(e) {
var thisClass = $(this).attr('class');
console.log(thisClass);
$('.video-container .video').each(function(){
var $this = $(this);
if ($this.is('.' + thisClass) ) {
$this.addClass('test');
}
})
e.preventDefault();
});
$('.video-tab-container ul li a').click(function(e) {
var thisClass, video;
thisClass = $(this).attr('class');
console.log(thisClass);
if ((video = $('.video-container .video.' + thisClass)).length !== 0) {
$(video).addClass('test');
}
e.preventDefault();
});

Add class to <li> when clicking on a link

That's the html of my menu:
<ul class="nav">
<li>A</li>
<li><a href="#b" >B</a></li>
<li><a href="#c" >C</a></li>
<li><a href="#d" >D</a></li>
</ul>
I want that, after I clicked on a link in the menu, the active class will be added to the clicked <li>.
Thanks in advance
Use jquery
$("li a").click(function() {
$('li a').not(this).removeClass('active');
$(this).toggleClass('active');
});
DEMO Updated
He is not asking for a jQuery solution. But that jQuery would be the ideal choice, here is how to do it with javascript, best practices, event delegation and modern. Perhaps someone learns something new from it as well.
http://jsfiddle.net/N9Hem/
window.onload = function(){
(function(){
var els = [];
var doc = document;
var get = function(id){return doc.getElementById(id);};
get('clickable').onclick = function(evt){
evt = evt || window.event;
var el = evt.target || evt.srcElement;
els = doc.querySelectorAll('#clickable a');
if(el.nodeName == "A"){
for(var i = els.length - 1; i >= 0; i -= 1){
els[i].className = '';
};
el.className = 'active';
};
};
})();
};
If you use jQuery then you could use code like this:
$(function () {
$(".nav a").click(function () {
$(".nav a").removeClass("active");
$(this).addClass("active");
});
});
Try this with jQuery
$('#nav li a').click(function(){
$('#nav li a').removeClass('active');
$(this).addClass('active');
});
Here is a prototype that doesn't use jquery as you didn't request it on your question.
It searches for the current element with the active class, remove it and add the class to the clicked one.
Javasript Function
function activeThis(element){
var current = document.getElementsByClassName("active")[0];
current.className = null;
element.className="active";
}
HTML code
<a href="#b" onclick="activeThis(this)">
I hope I got what you want... I add eventHandlers to <ul>. On click remove clicked from previous elem and set clicked-class (if current class is active??)
<ul class="nav">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
<script>
var clickedElem = null;
document.getElementsByClassName("nav")[0].addEventListener("click", function (e) {
if (clickedElem)
clickedElem.removeAttribute("class");
// check if e.srcElement.className is active?? that's what you want?
e.srcElement.className = "clicked";
clickedElem = e.srcElement;
});
</script>
This one should works for you
elems =document.getElementsByClassName("nav")[0].getElementsByTagName("a");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener("click", function (e) {
for (var i = 0; i < elems.length; i++) {
elems[i].className="";
};
this.className = "active";
});
}
I guess this will work
var navlinks = document.getElementByClass('nav').getElementsByTagName('a');
for (var i = 0; i < navlinks.length; i++) {
if(navlinks[i].className == 'active'){
navlinks[i].parentNode.parentNode.parentNode.className = 'YOUR CLASS';
}
}
Check my fiddle
I hope this is what you want
http://jsfiddle.net/arunberti/ftZzs/
a:visited
{
color:green;
}
a:active {color:yellow;}
a:link {color:red;}
Try this:
$('.nav li').click(function(e) {
$(this).addClass('selected').siblings().removeClass('selected');
});
Alternatively, if you want to attach the click event to the a:
$('.nav a').click(function(e) {
e.preventDefault();
$('.nav a').removeClass('selected');
$(this).addClass('selected');
});
Example fiddle
thats quite easy
jQuery CODE:
$('.nav li a').on('click',function(){
$('.nav li').each(function() {
var anc=$(this).find('a');
if(anc.hasClass('active'))
{
$(anc).removeClass('active');
}
})
$(this).addClass('active');
})
Edited:
Code is refined
Happy Coding :)

Getting Attr (ID) of Dynamically Added <li> Element with jQuery

I'm having issues getting ID of a dynamically added list element. Which is being added with the following:
$(".detail-view button").on("click", function(){
var noItems = $("ul#cart-items li").eq(0).attr("id");
var detailID = $(this).attr('id');
var orderTitle = $("#detail-"+ detailID + " span.order-title").text();
var insertTitle = $("<li><img src=\"/assets/images/global/intra_remove_item_btn.png\" />"+ orderTitle +"</li>").attr("id", detailID);
if(noItems == "emptycart") {
$("ul#cart-items li#emptycart").replaceWith(insertTitle);
$("#lp-orderform li:even").addClass("highlight");
} else {
$(insertTitle).insertAfter("ul#cart-items li:last");
$("#lp-orderform li:even").addClass("highlight");
}
});
Which updates my original HTML from the following...
<ul id="cart-items">
<li id="emptycart">You have no items in your cart.</li>
</ul>
And updates to...
<ul id="cart-items">
<li id="6955" class="highlight"><img src="/assets/images/global/intra_remove_item_btn.png">Chicken with Garlic Sauce</li>
<li id="6966"><img src="/assets/images/global/intra_remove_item_btn.png">Hunan Shrimp with Black Bean Sauce</li>
<li id="6965" class="highlight"><img src="/assets/images/global/intra_remove_item_btn.png">Hunan Pork with Black Bean Sauce</li>
</ul>
I'm trying to get the ID of the list item when a.remove-item is clicked to remove that list element.
$("ul#cart-items").live("click", "li a.replace-item", function(){
var removeItemID = $("li a.replace-item").attr("id");
alert(removeItemID);
});
But I only seem to get a value of "undefined". Any input would be greatly appreciated. Thank you!
Update
To get id of li on clicking <a> link
$("#cart-items").on("click", "a", function(){
var removeItemID = $(this).parent("li").attr('id');
alert(removeItemID);
});
Working jsFiddle
To get just id of clicked li use
$("#cart-items").on("click", "li", function(){
var removeItemID = $(this).attr('id');
alert(removeItemID);
});
Working jsFiddle
Your li element does't have remove-item class , but a hyperlink have
If you want to detect on li item click
$("#cart-items").on("click", "li", function(){
var removeItemID = $(this).find('a').attr("class");
alert(removeItemID);
});
Working jsFiddle
else if you want to detect on a hyperlink click
$("#cart-items").on("click", "a", function(){
var removeItemID = $(this).attr("class");
alert(removeItemID);
});
Working jsFiddle
The element that you are requesting the ID from doesn't have an ID. Try this code:
$("ul#cart-items").live("click", "li a.replace-item", function(){
var removeItemID = $(this).parent().attr("id");
alert(removeItemID);
});
if jQuery 1.7 or greater you should use on instead of live like so:
$("ul#cart-items").on("click", "li a.replace-item", function(){
var removeItemID = $(this).parent().attr("id");
alert(removeItemID);
});

Find the clicked li number

I have a standard list.
<ul>
<li>blah 1</li>
<li>blah 2</li>
<li>blah 3</li>
<li>blah 4</li>
</ul>
And my jQuery:
$('ul li a').live('click', function() {
var parent = $(this).parent('li');
});
What I want to find out is the parent li's position in the list of the clicked link e.g. clicking on blah 3 would give me 2, blah 4 would give 3 etc.
$('ul li a').live('click', function() {
console.log($(this).parent('li').index());
});
Will give you what you want, but keep in mind these are 0 based indexes -- ie the first line item is index 0, the last line item is 3.
jQuery index() method documentation
you can get the index of an element with jquery`s index
$('ul li a').live('click', function()
{
var index = $(this).index();
});
No need to jQueryfy this :
$('ul li a').live('click', function() {
var position = 0;
var currentNode = this;
var firstNode = currentNode.parentNode.firstChild;
while(firstNode != currentNode) {
position++;
currentNode = currentNode.previousSibling;
}
alert(position);
});
I know this is an old post, but .live is now deprecated in jQuery 1.7 and removed in jQuery 1.9.
The alternative is to use .delegate:
$('ul li').delegate('a','click', function() {
alert($(this).parent('li').index());
});
The index method should do what you want.
$(function() {
$('ul li a').live('click', function() {
var parent = $(this).parent('li');
alert(parent.prevAll('li').size());
});
});

Categories