jquery only appends last item [duplicate] - javascript

This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
I am trying to append multiple audio tags to the body of a document using jQuery:
$(function () {
var a = $("<div/>").text("hello");
$("body").append(a);
a.text("world");
$("body").append(a);
});
why isnt var a; being appended twice? I would at least expect "world" to appear twice (I understand I am overwriting "hello").

It's because the element in the a variable is already appended to the body, so the second line causes no change.
If you want two elements appended, you would need to create a second manually, or clone the first one:
$(function () {
var a = $("<div/>").text("hello");
$("body").append(a);
a.text("world");
$("body").append(a.clone());
});

basically you already inserted a div from one instance a variable
example: http://jsfiddle.net/kdKV8/4/
you could try cloning it.. clone()
$(function () {
var a = $("<div/>").text("hello");
$("body").append(a.clone());
a.text("world");
$("body").append(a);
});
http://api.jquery.com/clone/

you can also tried below code
$(function () {
$("body").append($("<div/>").text("hello"));
$("body").append($("<div/>").text("world"));
});

this might be easier...
$('body').append($('<div/>').text('Hello'), $('<div/>').text('World'));
made a fiddle: http://jsfiddle.net/filever10/Hh9hq/

Related

Global function not executing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have script that creates a div and adds a function that would remove this div on click, but it's not working.
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
}
Yes, yes, I KNOW this is not the best way to add a function, but I want to do it this way.
Just FYI - after executing create() the DIV appears fine. I checked and it does have proper ID and onclick="del(this.id)" attribute, but after clicking on it nothing happens. I double checked and added alert("I'm working") to the onclick attribute later and that worked. I'm not getting any errors. In the past .remove() was working fine but now it doesn't (Maybe that's because of the way I'm adding a function this time)
EDIT: It appears that del() is not executed when clicking on div.
You have this posted with jQuery, but you're showing mostly Vanilla. As to your initial problem,
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
$(element).html('<h1>DIV CREATED!</h1>').css('background-color', String.randColorHex());
}
create();
#someContainer > div { height: 10em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<div id="someContainer"></div>
Seems to work fine.
My guess would be that you have an issue with creating multiple divs by with the same ID, or possibly a scope issue.
Here's a couple steps you might take to double check the issue if using Google Chrome Dev Tools:
Open Console
Double Check function 'del' is globally available and the method you expect it to be by simply typing del. If you get an error, then your method may be displaced.
Another way you could check would be put the following in your onClick: try{console.debug(del);}catch(err){console.error('DEL DOES NOT EXIST!')}
Once you've established the method is within scope, if still not working, try the following:
Replace $("#"+el).remove(); with console.debug(el, $('#'+el))
This does a couple of things: It shows you that the Function is working, as well as gives you information of what's going on within.
If the first part of the console message (el) is the ID you expect, then check the 2nd part ($('#'+el)).
It should look something like: [div:#someID]
Open it and check it's length'. If0`, then it did not find that element.
If 1, then remove should be working fine. Put remove back in just above this console call, and ensure you now get a length of 0
Just FYI, this is how to do what you're trying to do using jQuery.
function create() {
var container = $('#someContainer'), // get container
// create div, everything in {} is an ATTR, then append it TO the container
div = $('<div />', { id: 'someID' + container.children('div').length+1 }).appendTo(container);
// just for visual, i use my own plugin to set a random background color
div.css('background-color', String.randColorHex());
}
$(function() {
$(document) // your click methods
.on('click', '#btnCreate', create)
.on('click', '#someContainer > div', function(e) { $(this).remove(); })
// trigger button once on load
$('#btnCreate').trigger('click');
})
#someContainer > div { height: 2em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<button id="btnCreate">Create</button>
<hr />
<div id="someContainer"></div>

trying to target a button created by JQuery [duplicate]

This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 7 years ago.
I'm trying to target a button I've created by pressing another button. My code technically works, but due to the size of what I'm doing, I'm trying to put the function of the second button press in another js file. That where I'm running into problems. My code is below.
$("#webCoding").on("click", function() {
if ( $( ".webCodingID" ).length ) {
return false;
}
picture.attr("src", "img/webCoding.jpeg");
$(".target").empty();
$(".jumbotron").hide();
var buttonGroup = $('<div role="group" aria-label="...">').addClass('btn-group-vertical center-block')
var buttonPhilosophy =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Design Philosophy")
var buttonStack =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Visit My Stack Overflow Account")
var buttonGithub =$("<button type='button' id='git'>").addClass("btn btn-default btn-lg").append("Look at what I've been doing on Github")
var webCodingID =$("<div>").addClass("trainingID")
$(buttonGroup).append(buttonPhilosophy).append(buttonGithub).append(buttonStack);
$('.target').append(buttonGroup).append(webCodingID);
// code for pressing created button is below.
$("#git").on("click", function() {
prompt("herro");
});
});
but I put this in another file (and get rid of the same code in the original js file), and nothing happens.
$(document).ready(function(){
$("#git").on("click", function(){
prompt("jungle boogie");
});
I can't figure out why. The js file is linked to my main page, I just can't get it to recognize buttons created by JS in another file.
You should bind the on to the body like so:
$("body").on("click", "#git", function(){
That should solve your problem I believe :)

for loop vs forEach in JavaScript -- example from book

I am currently learning JavaScript using O'Reilly's "Learning Web Application Development". In the example, we are constructing a website using HTML and CSS, which includes 3 tabs which should be able to be selected and become the "active" tab. The books claims that the following two ways of writing the tab code are equivalent:
1)
var main = function() {
"use strict";
var tabNumber;
for (tabNumber=1;tabNumber<=3;tabNumber++) {
var tabSelector = ".tabs a:nth-child("+tabNumber+") span";
$(tabSelector).on("click",function() {
$(".tabs span").removeClass("active");
$(tabSelector).addClass("active");
$("main .content").empty();
return false;
});
}
}
$(document).ready(main);
2)
var main = function() {
"use strict";
$(".tabs a span").toArray().forEach(function(element) {
$(element).on("click", function() {
console.print("this element: " + element);
$(".tabs span").removeClass("active");
$(element).addClass("active");
$("main .content").empty();
return false;
});
});
}
$(document).ready(main);
However, they do not output the same result. The version using forEach works correctly, so that when I click one of the tabs the attention moves to that tab and it becomes highlighted. However, in the version using a for loop, whenever I click any tab, the attention always moves to the last tab. To confirm what is happening, I printed out the name of the element inside the event listener with both methods, using 3 tabs total. And using the for loop, no matter which tab I click I am getting a response of
"this element: .tabs a:nth-child(3) span"
Could someone please help me explain why this is happening? Why is the output different using for or forEach? And why, using for, is it always passing the last element of tabs to the event listener?
Looks like there's a problem here:
var tabSelector = ".tabs a:nth-child("+tabNumber+") span";
$tabSelector.on("click",function(){
You've created a variable that doesn't have the $ at the beginning, then attached the event to a variable (not sure what it would refer to) with a $ at the beginning.
It should be changed to this, I believe:
$(tabSelector).on("click",function(){
In the for loop solution, you are setting tabSelector multiple times like so:
var tabSelector = ".tabs a:nth-child("+tabNumber+") span";
This selector is, in the end, going to be set to the last tabNumber, which is always going to be called when you make a reference to it:
$(tabSelector).addClass("active");
To avoid that, replace it by this, which will be different for each of them:
$(this).addClass("active");
JS Fiddle Demo

Need workaround for document.getElementById in order to cycle through multiple ID possibilities. Classes not working

I have 30 links in my HTML document, all of which, when clicked, trigger one specific div to change it's id using a js function.
Here are three of the 30 links followed by the single div with the id that changes.
Link 1
Link 2
Link 3
<div id="contain"></div>
Here is the div id change function (working, but not to my liking):
function changediv_1()
{
if (document.getElementById("contain")) {
document.getElementById("contain").setAttribute("id", "contain_1");
}
}
HERE IS THE PROBLEM: When I click Link 1 it changes the div id from "contain" to "contain_1", no problem there. Now the div name is "contain_1", so if I try to click Link 2 after clicking link 1 it won't work, because the div id is now "contain_1" and each function can only call for 1 id.
I need the above function to check for multiple divs (ie: #contain, #contain_1, #contain_2).
ideally like this:
function changediv_2()
{
if (document.getElementById("**contain, contain_1, contain_2, ...**")) {
document.getElementById("**contain, contain_1, contain_2, ...**").setAttribute("id", "contain_x");
}
}
I researched and tried applying .getElementByClass and it did not work - function seemed to only work with an id. There has to be a way around me posting the function 900 (no exaggeration) times to support each situation. Thank you so much for patience and reading my freaking novel of a post.
Try this use data and use on.click instead of inline javascript function
HTML
Link 1
Link 2
Link 3
<div id="contain" class="containDiv"></div>
jQuery
$(function () {
$('a').on('click', function () {
var contain = "contain_" + $(this).data('contain');
$('.containDiv').attr('id', contain);
//contain == contain_(1,2,3)
/*
Rest of your code to read from php and put into contain?
*/
});
});

.removeClass not functioning within .replaceWith

I'm trying to make a button that will hide a specific -- and then replace it with another hidden . However, when I test the code, everything fires correctly except for the .removeClass which contains the "display: none."
Here is the code:
<script type="text/javascript">
$(document).ready(function(){
var webform = document.getElementById('block-webform-client-block-18');
var unmarriedbutton = document.getElementById('unmarried');
var buyingblock = document.getElementById('block-block-10');
$(unmarriedbutton).click(function () {
$(buyingblock).fadeOut('slow', function() {
$(this).replaceWith(function () {
$(webform).removeClass('hiddenbox')
});
});
});
});
</script>
The CSS on 'hiddenbox' is nothing more than "display: none.'
There is a with the id of unmarried, which when clicked fades out a div and replaces it with a hidden div that removes the class to reveal it. However, the last part doesn't fire -- everything else does and functions properly. When I look at in the console too, it shows no errors.
Can someone please tell me where the error is? Thanks!
Edit: I may be using the wrong function to replace the div with, so here's the site: http://drjohncurtis.com/happily-un-married. If you click the "download the book" button, the the div disappears and is replaced correctly with the div#block-webform-client-block-18. However, it remains hidden.
The function you pass to replaceWith has to return the content you want to replace it with. You have to actually return the content.
I don't know exactly what you're trying to accomplish, but you could use this if the goal is to replace it with the webform object:
$(this).replaceWith(function () {
return($(webform).removeClass('hiddenbox'));
});
NB, use jquery !
var webform = $('#block-webform-client-block-18');
var unmarriedbutton = $('#unmarried');
var buyingblock =$('#block-block-10');
unmarriedbutton.click(function () {
buyingblock.fadeOut('slow', function() {
$(this).replaceWith( webform.removeClass('hiddenbox'));
});
});
Was too fast, i believe it's the way you select your object (getelementbyid) then you create a jquery object from it... -> use jquery API

Categories