JS problems with adding li - javascript

I have a problem with adding li. When I add new li text be in first li and should be in the next. https://jsfiddle.net/zaxmy1nw/1/
Probably problem is here.
function NewLI(){
AddLi;
userp.appendChild(userName);
LiP.appendChild(LiText);
var UladdLi = document.getElementById("chat").appendChild(AddLi);
var AddP = document.getElementById("lispan").appendChild(LiP);
var UseraddLi = document.getElementById("lispan").appendChild(userp);
}

You select by Id, but all li elements have the same id (lispan) so selecting by id will always return the first one.
What you can do is :
function NewLI(){
AddLi;
userp.appendChild(userName);
LiP.appendChild(LiText);
AddLi.appendChild(LiP)
AddLi.appendChild(userp)
var UladdLi = document.getElementById("chat").appendChild(AddLi);
}
see : https://jsfiddle.net/zaxmy1nw/2/

Related

How can I select the element of html file (except first and last) using DOM and manipulate it?

Here i want to select the second LI of UL using DOM and mainuplate it , i know how to select first and last element but i am not able to select second ,third and so on element . How to do it?
I want to change the "second" written on the html page(see picture 2 below) to my name using DOM.
let list = document.querySelector("ul").querySelectorAll("li");
for(let i = 1; i < list.length - 2; i++){
list[i].doSomething();
}
You can use querySelectAll and length proprety like this:
var el = document.querySelectorAll('ul > li');
el[el.length-2].textContent="Shubham Kandpal";
or using jquery's eq() method like this:
$("ul > li").eq(-1).text("Shubham Kandpal");
Use nth-child
ul > li:nth-child(2)
Please use this javascript selector to select the Second (LI) option.
document.querySelector('ul li:nth-child(2)')
Another possible way, besides querySelector, is by adding a class or an Id and getting it:
Adding using a class
function myFunction() {
let x = document.getElementsByClassName("className");
x[1].textContent = "Whatever you want to name it now";
// 1 because it is the second position
}
or by id
function myFunction() {
let x = document.getElementById("idName");
x.innerHTML = "Whatever you want to name it now";
// You can also use innerHtml to change the text
}

Removing an array element by clicking an HTML <li>

So I'm doing a playlist manager for youtube (using the ytb api) and for the graphic part I'm doing, such as youtube has, a list of every thumbnail there is in a given playlist. I use an HTML 'ul' and add every thumbnail as a 'li'.
Everything is working fine but id like to add a feature so the user could click on one of the thumbnails to remove it from the playlist.
First, let me explain how the important part is coded.
I use an array as a queue to stock every video ID that will be played (this is the playlist) :
var queue = []
And for the thumbnail list I use this function :
function refreshThumbnailsQueue() {
var thumbnailsUl = document.getElementById('thumbnailslist');
while(thumbnailsUl.firstChild) {
thumbnailsUl.removeChild(thumbnailsUl.firstChild );
}
for (var i = 0; i <= queue.length - 1; i++) {
var thumbnail = 'http://img.youtube.com/vi/' + queue[i] + '/maxresdefault.jpg';
var newLi = document.createElement('li');
newLi.className = 'thumbnailLi';
newLi.onclick = function() {
removeFromQueue();
}
var newImg = document.createElement('img');
newImg.className = 'thumbnailImg';
newImg.src = thumbnail;
newLi.appendChild(newImg);
thumbnailsUl.appendChild(newLi);
}
}
So I'm just removing every child the ul has and then filling it with every thumbnail of the video IDs there are in my queue var.
As you can see, there is a removeFromQueue() function called with an onclick event on each li in the code, and this is what I try to code.
Basicaly, if you click the third li, it should remove the third element of my queue var.
If you have any ideas, please let me know. (and BTW sorry for the mistakes English isn't my main language)
Thanks!
Note : I dont want to use jQuery.
If jQuery is an option, you can simply do the following :
$( "li" ).click(function(){
$( this ).remove();
})
As simple as that. If you want more information, I'll update my answer.
You can also visit this page for plain old javascript. Here is the important part :
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
As for the index of the li element
When you insert the list item in the DOM, you also set it's ID like this :
function refreshThumbnailsQueue() {
...
for (var i = 0; i <= queue.length - 1; i++) {
...
// Create the li.
var newLi = document.createElement('li');
newLi.id = "song-" + i;
// Create the onclick listening
li.onclick = function(){
// Remove from DOM.
var elem = document.getElementById(this.id);
elem.parentNode.removeChild(elem);
// We keep only the integer (index)
// In this example, '5' cuts away the "song-".
var index = parseInt((this.id+"").substring(5));
// Then, we remove it from the list.
YourProgram.removeIndex(index);
}
...
thumbnailsUl.appendChild(newLi);
}
}
This way, you know what it's index is.
Hope it helps.
Pass the index of the element to remove to the removeFromQueue(), like removeFromQueue(i). Then remove the item from queue.
function removeFromQueue(index) {
queue.splice(index, 1)
refreshThumbnailsQueue()
}

JavaScript Not able to set focus to first li element within ul

I have below code:
<ul id='someId'>
<li class='someClass'>
</li>
</ul>
I want to set focus on first li element within ul based on some condition.
My first attempt is like this:
var ul = document.getElementById('someId');
var child = ul.childNodes[0];
child.focus();
My second attempt is like this :
var y = document.getElementsByClassName('someClass');
var aNode = y[0];
aNode.focus();
But none of the above works
Any ideas?
The problem is that you can't focus a non input element without setting tabIndex.
<li tabIndex="-1">...</li>
You can Try this fiddle: jsfiddle
An 'li' can't have focus, however an 'input' can, so you write yourself the following script:
function installLI(obj){
var ul = document.createElement('ul');
obj.appendChild(ul);
var li = document.createElement('li');
var txt = document.createElement('input');
li.appendChild(txt);
ul.appendChild(li);
txt.focus();
li.removeChild(txt);
}
Where 'obj' is the object (like an editable div) that you're appending your list to.

Text input inserting wrong value into list item

Here is my code: http://jsfiddle.net/H5bRH/
Every time I click on the submit button, it should insert what I typed into a new li item.
But instead of that, it inserts what I typed the first time PLUS the new value that I typed. Play with my jsfiddle to see what I mean.
How do I fix this so that it only adds what the user inputs into the form?
I assume there's something wrong here:
function saveTweet() {
var tweet = document.getElementById("tweet");
var tweetName = tweet.value;
var li = document.createElement("li");
li.innerHTML = tweetName;
var ul = document.getElementById("tweets");
ul.appendChild(li);
}
You have attached 2 click event to save button.
button.onclick = saveTweet;
Using jQuery $("#saveTweet").click(function ()
$("#saveTweet").click(function () {
var tweet = document.getElementById("tweet");
var tweetName = tweet.value;
var li = document.createElement("li");
li.innerHTML = tweetName;
var ul = document.getElementById("tweets");
ul.appendChild(li);
$("li").slideDown("fast");
});
JSFiddle
Why not just reduce all that code to :
$("#saveTweet").click(function () {
$('#tweets').append('<li>' + $("#tweet").val() + '</li>')
$("li").slideDown("fast");
});
jsFiddle example
Instead of having two click handlers for the #saveTweet button, move the slideDown call to your saveTweet function.
function saveTweet() {
var tweet = document.getElementById("tweet");
var tweetName = tweet.value;
var li = document.createElement("li");
li.innerHTML = tweetName;
var ul = document.getElementById("tweets");
ul.appendChild(li);
$("li").slideDown("fast");
}
It happens because you bind two click handlers on the #saveTweet element.
One to add the content, and one to animate the li elements..
In your case the animated one is occuring first and the appending second.. so you always animate the previously added element...
Since you use jQuery anyway, why not use that for all your interactions ?
$(function () {
var button = $("#saveTweet");
button.on('click', function () {
var tweet = $("#tweet"),
ul = $("#tweets"),
tweetName = tweet.val(),
li = $('<li>', {html: tweetName});
ul.append(li);
li.slideDown("fast");
});
});
Demo at http://jsfiddle.net/gaby/Y9cY3/1/

JQuery: loosing the <tr> id when using replaceWith() method

I am trying to implement a function which will change the elements order in a table. The logic is very easy: Each TR (except the first and the last ones) has a button_up and a button_down. When the user clicks one of those buttons, the element will change his place with the one above or below.
To do this, I am using jQuery and each TR has a unique Id and the buttons have a common class.
When a button with the specific class is clicked, I am executing this JavaScript code:
$('.upArrow').click( function(something)
{
var id = $(this).attr("id");
var n=id.split("_");
var new_id = '#row_'+n[1];
var parent =$(new_id);
var prev = $(new_id).prev();
swap(prev, parent);
init_authors_list_ordering();
});
$('.downArrow').live('click', function()
{
var id = $(this).attr("id");
var n=id.split("_");
var new_id = '#row_'+n[1];
var parent =$(new_id);
var next = $(new_id).next();
swap(next, parent);
init_authors_list_ordering();
});
}
function swap(a, b, direction)
{
var html = a.wrapInner('<tr></tr>').html();
a.replaceWith(b.wrapInner('<tr></tr>').html());
b.replaceWith(html);
}
The problem is that: The first time, everything works fine (my funxtion is not finished, I have to set some other parameters on change but the logic is there). But then, The two elements who changed their place have lost the TR's id, so they can't be touched anymore.
I don't know why the id is lost. This is the replaceWith() method.
Any help is welcome. Thank you.
To swap the elements, simply do:
function swap(a, direction, b) {
a[direction](b);
}
and call like:
var firstElem = $('#divID'),
secondElem = $('#divID');
swap(firstElem, 'before', secondElem); // or after, whatever you need ?
FIDDLE
Your constant <tr></tr> has no id attribute, so it ends up with no id attribute.
EDIT:
Here is what I reference:
function swap(a, b, direction)
{
var html = a.wrapInner('<tr></tr>').html();
a.replaceWith(b.wrapInner('<tr></tr>').html());
b.replaceWith(html);
}

Categories

Resources