jQuery adding element to dynamic element - javascript

I have a dynamically added div which I want to append in response to a click event.
The initial div is created and rendered when added however trying to add children divs to the first dynamic div does not render - yet in console log the dynamic div shows the new div has been added.
var newDiv = $('<div id="#newDiv'+pID+'" />').css({
display:"inline-block",
width:"90%",
height:"100px",
position:"relative"
})
var newHTML = "<div>some content</div>"
$(newDiv).html(newHTML)
$('#dynDiv'+ID).append($(newDiv))
console.log($('#dynDiv'+pID)) // displays code created successfully
So newDiv is not rendered nor present when "inspecting" the DOM using debugger.
Why is the second attempt to add dynamic content failing ??

Have you remembered to append it to something? Remember, jQuery can have DOM elements present in memory which are not part of the page:
newDiv.appendTo($(parentElement));
eg. http://jsfiddle.net/dTe73/
A couple of other possible errors:
# is not a valid character to put in an id in $('<div id="#newDiv'+pID+'" />')
$('#dynDiv'+ID) looks like a typo for $('#dynDiv'+pID) (or the other way around)
Not an actual error, but redundant use of $: $(newDiv) is absolutely equivalent to newDiv

I found the source of the problem was that the parent div to which I was adding the dynamic div was not unique - there were multiple elements with same name ! This makes sense that it would fail. Thanks for everyones input.

Replace $(newDiv).html(newHTML) with newDiv.html(newHTML)
and $('#dynDiv'+ID).append($(newDiv)) with $('#dynDiv'+ID).append(newDiv)
and it should work.

Related

Jquery put elements in div

You need to put items in a div - <div style = 'flex-direction: column;'>.
Div needs to be created after p withid = "billing_city_field"
and closes after the p withid = "apartment_field".
Tried to do it with this function:
jQuery (document) .ready (function ($) {
$ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
$ ("# apartment_field"). after ("</ div");
});
But the div immediately closes. What should I do?
The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.
Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:
jQuery($ => {
let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
$contents.wrapAll('<div class="column" />');
});
Note the use of a class attribute in the above example, instead of applying inline style rules.
Question is not super clear but from what I can tell.
I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.
Simplest way to do this, if these things needs to created and don't exist already on body for example.
$(function(){
var p = $("<p id='apartment_field'>Paragraph test</p>");
$("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
$("#billing_city_field").html(p);
});
I've added Paragraph test so result is visible easier.
And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.
$("#billing_city_field")
$("#apartment_field")
Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.
$("#billing_city_field").append($("#apartment_field").detach());

jQuery insert child into element at set index

I would like to use jQuery to insert an html element inside another element and at a particular position.
I've found a way I can do it in Javascript but was wondering if there's a shorter 'one line of code' way of doing it in jQuery.
var container = document.getElementById("container");
container.insertBefore( html, container.children[0] );
Many thanks in advance
Use the selector for the n-th child of a given kind and the before method (assuming your new content comes in html) :
$("#container > div:nth-of-type(42)").before(html);
If you want to insert a new element as the first or last child of a container, there is another api option:
$("#container").append( html );
$("#container").prepend( html );
(For the sake of completeness, append / prepend are the links into the jQuery API docs)
If you want to add an element inside an other with jquery, you have to do like this :
$('#container').append(html);

Dynamic creation and selection of html elements via jquery

How can I access the dynamically created html element by its Id on very next line of this following code?
var line = $('<div class="showInGrid" id="removeMeLater">
<span class="dateP" id="calendar' + ind + '" ></span>
</div>');
I want to access it like the following line of code.
$("#calendar"+ind).datepicker({});
However I'm able to link the datepicker with it like the following.
line.datepicker({});
But obviously it is not giving me the desired result and it gets created every time loop iterates over it.
The problem is you have not added the element to the DOM.
jquery selector will search inside the DOM. since the element is not in DOM it will return an empty array.
run $("#calendar"+ind).datepicker({}); after appending it to the body

Meaning and usage of jquery find('>')

I'm working on a javascript code which does :
$('div').html(<some text>).find('>')
Looking at the jQuery documentation, I can't understand what find('>') is supposed to do.
Moreover, when experimenting in navigator console, I get strange results :
$('div').html('to<br/>to').find('>') -> [ <br>​, <br>​, <br>​]
$('div').html('to<a/>to').find('>') -> [ <a>​</a>​, <a>​</a>​, <a>​</a>​]
Why a 3 times repetiton ?
So, can anyone enlighten me about this strange find('>') ?
> is the Child Combinator CSS selector. .find('>') will pull all direct children of the element.
As mentioned in comments, the repetitions must be due to your document having multiple div elements.
Update
From your comment:
I thought the line was creating a div then setting some html into it.
$('div') itself selects all div elements which exist within document. If you want to create a div element, you can instead do this:
$('<div/>', { html: 'to<br/>to' });
If you're new to jQuery, I'd strongly advise checking out http://try.jquery.com and http://learn.jquery.com.
As someone pointed out, '>' selects the child elements of an element.
Why 3? Because surely you have 3 divs, so
$('div') //selects 3 divs
.html(...) // adds content to each div
.find('>'); //return the direct descendants of each element in the jQuery object
//as a new jQuery object

Adding and finding classes that is dynamically added to body - jquery

Is there any way to add classes or alter objects that is dynamically added to the body?
I am adding a range of objects to the body by javascript.
Fot instance Im adding some links that is dynamically generated and added to the body. When they are loaded I need to elect the first of the divs and add a new class to it.
I can't seem to find any way to do this... Update the DOM or how should I go around this? There must be a way to alter dynamically added objects.
Any clues?
Thanks for any help!
if you added them dynamically, then you can just use the objects you already have. Otherwise you'll need to find them with sizzle.
//create the elements
var $link1 = $('<a>click me</a>').attr('href','page1.html');
var $link2 = $('<a>click me</a>').attr('href','page2.html');
//append the elements
$('#some-links').append($link1).append($link2);
//use the element we created
$link1.addClass('my-class');
//find the second link element using sizzle
$('#some-links>a').eq(1).addClass('my-other-class');
demo: http://jsfiddle.net/PtebM/2/
Well of course you caN:
var a = $('<a>');
a.html('new link').appendTo('#menu');
a.addClass('border');
or
var a = $('<a>');
a.html('new link').appendTo('#menu');
$('#menu a').addClass('border');
fiddle http://jsfiddle.net/4NPqH/
Why not just add a class name to your generated elements?.
I.e.:
$('span').html('Hello world').addClass("fancyText").appendTo('body');

Categories

Resources