javascript equivalent of jquery for this function - javascript

In a dinamically generated "ol" :
document.getElementsByTagName('ol');
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML = (results.rows.item(i).location + "-" + results.rows.item(i).datte);
newLi.appendChild(link);
olnew[0].appendChild(newLi);
i need find the "li" clicked, i use jquery library only for this function, i am searching for the same functionality in javascript, but at momento i have not idea how i can code it. thx
var ss;
ss=$("#idfromOl");
ss.click(clickhecho);
}
function clickhecho()
{
var $all_lis = $('li');
$all_lis.on('click', function() {
var index = $all_lis.index(this);
});
}

try this:
function createfunc(i) {
return function() { alert(i); };
}
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML ="test"
newLi.appendChild(link);
// just add onclick event; use createFunc to create function closure (otherwise 'i' would always be the last 'i'
newLi.onclick = createfunc(i);
olnew[0].appendChild(newLi);
}

I might be mistaken, but is this what you are looking for?
var elements = document.getElementsByTagName('li');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function (e) {
$("#clickedLi").text(e.srcElement.id);
});
}
It appends an event called addEventListener to every li element.
Inside each li element there is an click event given as a parameter which contains the id of the li clicked.
demo: http://jsfiddle.net/DUzMc/1/

Your first part of script is incomplete, so I did a short script to generate a dynamic list.
Basicly you were looking for addEventListener():
var elements = 10;
ol = document.createElement('ol');
for(i = 1; i <= elements; i++){
var li = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href', '#');
a.text = 'Link ' + i;
li.appendChild(a);
ol.appendChild(li);
a.addEventListener("click", who, false); // THIS IS THE IMPORTANT PART
}
document.getElementsByTagName('body')[0].appendChild(ol);
function who(e){
var myTarget = e.target;
myTarget.text = "clicked!";
}

The easiest way is to include the event while generating the list:
document.getElementsByTagName('ol');
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML = (results.rows.item(i).location + "-" + results.rows.item(i).datte);
// Add this
link.onclick = function(index) { return function() {
// do something with index variable
}}(i);
newLi.appendChild(link);
olnew[0].appendChild(newLi);
Note I use a local variable index instead of i, this is because when the item is clicked the value of i will be different (equal to len).

Related

JavaScript Creating Buttons in a loop

I want to break and center after each button, any suggestions? setAttribute did not work and does not add the breaks
for (var j = 0; j <= 6; j++) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(sm[j] + " " + sy[j]);
btn.appendChild(t);
document.body.appendChild(btn);
}
jsfiddle
HTML
<div id='theParent' class='center_the_stuff'>
</div>
JS
function addInput(type, value, name, id, onclick, parentId) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = value; // Really? You want the default value to be the type string?
element.name = name; // And the name too?
element.id = id;
element.onclick = onclick;
var parent = document.getElementById(parentId);
//Append the element in page (in span).
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
window.onload = function () {
for (var j = 0; j <= 6; j++) {
var temp = 'mybutton' + j;
addInput('button', temp, temp, temp, undefined, 'theParent');
addBreak('theParent');
}
}
CSS
.center_the_stuff {
text-align: center;
}

I need to put my LI array element into a UL but I cant

HERE IS THE CODE:
I need to do a couple of things but I am pretty new coding :S.
First I need to format the li elements I am loading into the array into a UL. them I need also to create a loop where I can print those 20 array elements repeating them to display 2300 elements. Thanks :)
var _objetsOfArray = new Array();
var darFormato = function (numero){
var numero = document.createElement("li");
var contenido = document.createTextNode(i);
numero.appendChild(contenido);
document.body.insertBefore(numero);
}
for (i = 0; _objetsOfArray.length < 20; i++ ){
_objetsOfArray.push (i);
darFormato(i);
};
This resolved it for you.
http://jsfiddle.net/t4Vec/
var count = 2300;
while (count){
var _objectsOfArray = [],
ul = document.createElement("ul");
for (var i = 0; i < 20; i++){
var item = document.createElement("li");
item.innerText = i;
_objectsOfArray.push(item);
ul.appendChild(_objectsOfArray[i]);
count --;
}
//do something with UL
document.body.appendChild(ul);
}
If you have a precreated list, you could use innerHTML and parse it accordingly.
My sample just prints a ul with 20 Li elements with the text node set to the index of the node
Edit: New Fiddle: http://jsfiddle.net/t4Vec/1/
I use this on a page to generate some dynamic links:
<ul id="list">
</ul>
and here is the script
var myData = [
"item1",
"item2"
]
function createItems()
{
var ul = document.getElementById("list");
for (var i = 0; i < myData.length; i++)
{
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "http://stackoverflow.com/search?tab=newest&pagesize=30&q=" + myData[i].toLowerCase();
a.target = "_blank";
a.innerHTML = myData[i];
li.appendChild(a);
ul.appendChild(li);
}
}
createItems();
where I changed the hrefs to SO :)
I hope taking a look will help you

How to add a document fragement to a div

I have this simple code. I need to add this ul html list to "my-div", but with this code I cannot add it. Any idea what is wrong?
Would be possible add the fragmentusing jquery?
this.renderMenuTop = function() {
var menu, f, ul;
menu = ['menu-actuality', 'menu-archive', 'menu-pdf', 'menu-pictures'];
f = document.createDocumentFragment();
ul = document.createElement('ul');
for (var i = 0; i < menu.length; i++) {
var li = document.createElement('li')
li.id = menu[i];
ul.appendChild(li);
}
document.getElementById("my-div").appendChild(f);
//$(this.elmMenuTop).append(f);
}
You never add any elements to your document fragment. Add this after your for loop:
f.appendChild(ul);
Another option is to just dump the document fragment altogether and just:
document.getElementById("my-div").appendChild(ul);
// ^^ Change from f to ul
You never put anything in f. But why do you even have a document fragment?
this.renderMenuTop = function() {
var menu = ['menu-actuality', 'menu-archive', 'menu-pdf', 'menu-pictures'];
var ul = document.createElement('ul');
for (var i = 0; i < menu.length; i++) {
var li = document.createElement('li')
li.id = menu[i];
ul.appendChild(li);
}
document.getElementById("my-div").appendChild(ul);
//$(this.elmMenuTop).append(f);
};
If you need to append it to two different things, a document fragment won’t help.
Where do you add the list to the fragment? You'd need to add
f.appendChild(ul);
before adding it to the div. Alternatively, just add the list straight to the div without the fragment.
To answer the second part of your question, this is also possible with jQuery:
this.renderMenuTop = function() {
var menu = ['menu-actuality', 'menu-archive', 'menu-pdf', 'menu-pictures'];
var $ul = $('<ul></ul>');
for (var i = 0; i < menu.length; i++) {
$ul.append('<li>' + menu[i] + '</li>');
}
$('#my-div').append($ul);
}

How to Change All Links with javascript

I want to change all links of my site. Suppose a link given by .Example http://www.google.com/ changes to http://www.mysite.com/?redirect=http://www.google.com/
i have my own redirector just i need to change the links via javascript for all url
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "http://www.mysite.com/?redirect=" + anchors[i].href
}
You can then make the code run on page-load by wrapping it in a function linked to window.onload event:
window.onload = function() {
/* onload code */
}
If you use javascript without a framework, you can use the following lines:
var links, i, le;
links = document.getElementsByTagName('a');
for (i = 0, le = links.length; i < le; i++) {
links[i].href = "http://www.mysite.com/?redirect=" + encodeURIComponent(links[i].href);
}
Just another version with some checks for local links and .forEach()
var links = [].slice.apply(document.getElementsByTagName("a"));
links.forEach(function(link) {
var href = link.href;
if (href.length && href.substring(0, 1) !== "#" && href.substring(0, 1) !== "/") {
link.href = "http://www.mysite.com/?redirect=" + encodeURIComponent(link.href);
console.log(link.href);
}
});
$('a').each(function(i, e)
{
var current = $(this);
current.attr('href', 'http://www.mysite.com/?redirect=' + encodeURIComponent(current.attr('href')))
});

JavaScript and the DOM Manipulation (Creating and Deleting)

So I'm trying to to basically dynamically create li's inside an array, and I would like to create a 'delete' button within each li, so that when I click that li, I can delete that specific li.
I know this seems very basic, but I've been looking at JS for hours now, and am starting to really confuse myself here.
I keep getting errors like addChild() is not a function... I feel like I'm close, but no cigar. Thanks in advance!
Anyway, here's my add function:
function add(){
var deleteBtn = document.createElement('input');
deleteBtn.type = 'submit';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
for(i=0;i<1;i++){
id_number[i] = i+1;
var newSong = '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
// $(newSong).appendChild(deleteBtn);
$(deleteBtn).appendTo("#playlist-1");
$(newSong).appendTo("#playlist-1");
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(newSong);
});
}
}
Here's my delete function
function deleteFromPlaylist(newSong){
var deleteBtn = document.getElementsByTagName('deleteButton');
// var deleteMe = deleteBtn.parentNode;
alert(deleteBtn);
for(i=0;i<showList.length;i++){
if(newSong === showList[i]){
showList.splice(i,1);
// var pp = p.parentNode;
// pp.removeChild (p);
deleteMe = deleteMe.parentNode.remove("li_test");
deleteMe.removeChild(deleteBtn);
}
// console.log(deleteMe);
}
}
EDIT: 1 More Related Question
I would like to only add an item if it doesn't exist already in the array. Here is what I have so far. Any tips on where I'm going wrong?
for (i = 0; i < showList.length; i++) {
if (newSong !== showList[i]){
ul_list.innerHTML = newSong;
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
alert("It IS in the Array!");
}else{
alert("This already exists!");
}
}
You seem to have a strange mix of code. Forget the jQuery stuff until you know javascript.
> function add(){
> var deleteBtn = document.createElement('input');
> deleteBtn.type = 'submit';
I don't think that's a good idea. Much better to use type button or a button element.
> deleteBtn.name = 'addButton';
> deleteBtn.className = 'deleteButton';
>
> for(i=0;i<1;i++){
Presumably i will go a bit higher in future. ;-)
> id_number[i] = i+1;
Where did id_number come from?
>
> var newSong = '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
> // $(newSong).appendChild(deleteBtn);
Stick to one method of creating elements. Consider using a document fragment to hold the parts.
> $(deleteBtn).appendTo("#playlist-1");
> $(newSong).appendTo("#playlist-1");
> showList.push(newSong);
Where did showList come from?
> deleteBtn.addEventListener('click', function(evt) {
> deleteFromPlaylist(newSong);
> });
Not all browsers support addEventListener. Since you are only adding one listener, consider just assigning to the button's onclick property. Note that newSong is just a string.
> }
> }
In the other function:
> function deleteFromPlaylist(newSong){
> var deleteBtn = document.getElementsByTagName('deleteButton');
There is no HTML "deleteButton" element, so that will return an empty collection.
> // var deleteMe = deleteBtn.parentNode;
> alert(deleteBtn);
> for(i=0;i<showList.length;i++){
> if(newSong === showList[i]){
> showList.splice(i,1);
> // var pp = p.parentNode;
>
> // pp.removeChild (p);
> deleteMe = deleteMe.parentNode.remove("li_test");
Where did deleteMe come from? You commented out where it was declared and it hasn't been assigned a value, so deleteMe.parentNode will throw an error.
> deleteMe.removeChild(deleteBtn);
> }
> // console.log(deleteMe);
> }
> }
> }
Anyhow, here's some working code, it's still pretty awful but I'll leave it to you go improve it.
<script>
var showList = [];
function add(){
var id_number = [];
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
deleteBtn.value = 'Delete Button';
for (i=0; i<1; i++) {
id_number[i] = i + 1;
// '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
var newSong = document.createElement('li');
newSong.className = 'li_test';
newSong.id = id_number[i];
newSong.appendChild(document.createElement('span').appendChild(document.createTextNode('song')));
showList.push(newSong);
deleteBtn.onclick = (function(id) {
return function(){deleteFromPlaylist(id);}
}(newSong.id));
newSong.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(newSong);
}
}
function deleteFromPlaylist(id) {
var song = document.getElementById(id);
if (song) {
song.parentNode.removeChild(song);
}
}
window.onload = function() {
add();
}
</script>
<ul id="playlist-1">
<li>Original
</ul>
I've altered your code and functions to purely use javascript, instead of a mixture containg jquery. I've added comments in the code to explain my actions. If you have any questions, feel free to ask.
var showList = [];
var inc = 1;
function add() {
//create the container element. If we do this, keeping track of all elements
//becomes easier, since we just have to remove the container.
var container_div = document.createElement('div');
container_div.id = "cont_" + inc;
var ul_list = document.createElement('ul');
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.value = 'remove song';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
var id_number = [];
var newSong = "";
for (i = 0; i < 1; i++) {
id_number[i] = i + 1;
newSong += '<li class="li_test" id="cont_' + inc + '_song_id_' + id_number[i] + '">' + "<span>test " + inc + "</span>" + '</li>\n'; //all ids must be unique, so we construct it here
}
ul_list.innerHTML = newSong;
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
}
function deleteFromPlaylist(evt, newSong) {
var deleteBtn = evt.target; //target the button clicked, instead of a list of all buttons
var container_div = deleteBtn.parentNode; //get the parent div of the button
var cont_parent = container_div.parentNode; //and the parent of the container div
for (i = 0; i < showList.length; i++) {
if (newSong === showList[i]) {
showList.splice(i, 1);
}
}
cont_parent.removeChild(container_div); //finally, remove the container from the parent
}
Update:
I've modified the above function to strictly use objects, rather than strings, because it is easier to extract relevant information from objects, than strings.
I've added in comments to assist with understanding the code. Again, if you have any questions, feel free to ask.
function add() {
var list_bool;
//create the container element. If we do this, keeping track of all elements
//becomes easier, since we just have to remove the container.
var container_div = document.createElement('div');
container_div.id = "cont_" + inc;
var ul_list = document.createElement('ul');
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.value = 'remove song';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
var list_item = document.createElement("li"); //create list element
list_item.className = "li_test"; //set element class
var list_span = document.createElement("span"); //create span element
list_span.innerHTML = "test"; //set span text
list_item.appendChild(list_span); //append span to list element
ul_list.appendChild(list_item); //append list element to un-ordered list element
var list_bool = false; //create local boolean variable
if (showList.length > 0) { // loop through showList if it isn't empty
for (var i = 0; i < showList.length; i++) {
if (showList[i].innerText !== list_item.innerText) {
list_bool = true; //if song exists(comparing text values, set bool to true
} else if (showList[i].innerText === list_item.innerText) {
list_bool = false; //else, set it to false
break; //break out of loop.. we don't want it becoming true again, now do we?
}
}
} else {
list_bool = true; //showList is empty, set to true
}
if (list_bool) { //if true, do action of appending to list
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(list_item);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
}
}
DEMO, notice that add() is executed twice, but because the song 'test' already exists, it only executes the end action once.

Categories