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
Related
I need to be able to select and modify an element in an HTML document. The usual way to find an element using jQuery is by using a selector that selects by attribute, id, class or element type.
However in my case I have the element's HTML DOM and I want to find the element on my document that matches this DOM.
Important :
I know I can use a class selector or ID selector etc.. but sometimes the HTMLs I get don't have a class or an ID or an attribute to select with, So I need to be able to select from the element's HTML.
For example here is the element I need to find :
<span class='hello' data='na'>Element</span>
I tried to use jQuery's Find() but it does not work, here is the jsfiddle of the trial : https://jsfiddle.net/ndn9jtbj/
Trial :
el = jQuery("<span class='hello' data='na'>Element</span>");
jQuery("body").find(el).html("modified element");
The following code does not make any change on the element that is present in my HTML and that corresponds to the DOM I have supplied.
Is there any way to get the desired result either using native Javascript or jQuery?
You could filter it by outerHTML property if you are sure how browser had parsed it:
var $el = jQuery("body *").filter(function(){
return this.outerHTML === '<span class="hello" data="na">Element</span>';
});
$el.html("modified element");
el = jQuery('<i class="fa fa-camera"></i>');
This does not say "find the element that looks like <i class="fa fa-camera"></i>". It means "create a new i element with the two classes fa and fa-camera. It's the signature for creating new elements on the fly.
jQuery selectors look like CSS, not like HTML. To find the i element with those two classes, you need a selector like i.fa.fa-camera.
Furthermore $("document") looks for an HTML element called document. This does not exist. To select the actual document, you need $(document). You could do this:
$(document).find('i.fa.fa-camera').html("modified html")
or, more simply, you could do this:
$('i.fa.fa-camera').html('modified html');
You indicate in a comment to your question that you need to find an element based on a string of HTML that you receive. This is, to put it mildly, difficult, because, essentially, HTML ceases to exist once a browser has parsed it. It gets turned into a DOM structure. It can't just be a string search.
The best you can do is something like this:
var searchEl = jQuery('<i class="fa fa-camera"></i>');
var tagName = searchEl.prop('tagName');
var classes = [].slice.apply(searchEl.prop('classList'));
$(tagName + "." + classes.join('.')).html('modified html');
Note that this will only use the tag name and class names to find the element. If you also want IDs or something else, you'd need to add that along the same lines.
You should use Javascript getting the elements by something like
document.getElementById...
document.getElementsByClassName...
document.getElementsByTagName...
Javascript is returning the elements with the Id, Class or Tag Name you chose.
You can get en element with document.querySelector('.fa-camera')
with querySelector you can select IDs and Classes
You can simply refer to it by its class names.
$('.fa.fa-camera').html("modified html");
Similar to this answer https://stackoverflow.com/a/1041352/409556
Here is a full example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.fa.fa-camera').html("modified html");
});
</script>
</head>
<body>
<i class="fa fa-camera"><h1>Some HTML</h1></i>
</body>
</html>`
The one thing that you could use is to check attributes (class and id goes here too in some way) that element have, and the build jQuery selector or DOM querySelector to find the element you need. The hardest part would be to find element based on innerHTML property - "Element" text inside it, for this one you'll probably have to grab all similar element and then search through them.
<span class='hello' data='na'>Element</span>
jQuery('body').find('span.hello[data=\'na\']').html('modified element')
Take notice of 'span' - that's tag selector, '.hello' - class, '[data="na"]' data attribute with name of data.
Jsfiddle link here that extends your example;
I need the id(and other attributes such as value) of a span i previously created on an ajax event.
Is there a way to do this?
This is how the span is created on php post:
echo "<span class='non-skin-symptom-choice disease_option' ".
"onclick='showinfo(".$var[0].");' id=".$var[0].">"
.$var[1]." -- ".number_format($var[3]*100, 2, '.', '')."%</span>";
and I want to get its id whenever a checkbox is clicked.
$(".chb").click(function(){
var id= $(this).attr('id');
var list=[];
$('.disease_option').each(function (){
alert("this.val=="+ $(this).attr("val")); //i need the value here
var str= $(this).attr("value").split(" -- ")[1];
alert(str);
str=str.slice(0,str.length - 1);
if(parseFloat(str) >=support)
list.push(id) //i need the id here
});
the checkbox is not dynamically created, so $(".chb").click(function(){} works.
somehow, $(this).attr("id") works but $(this).attr("val") returns undefined... i also tried $(this).attr("value") but same results. $(this).val returns empty.
use
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
as this have a high level event attachment and it can get the elements who have been created on a runtime
Try this
alert($(".non-skin-symptom-choice").attr("id"));
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have create a "delegated" binding by using on()
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
possible duplicate: Click event doesn't work on dynamically generated elements
If your DOM node did not exist when the page loaded (ie. it was added to the page via AJAX after the page loaded), jQuery cannot see it if you try to update it or read it with jQuery methods. One way to overcome this is to set up your jQuery function to reference the class or ID of the parent of the node you want to target (assuming the parent class is loaded into the page on page load), along with the class of the node you want to target. For example:
$(".chb").click(function(){
var id = $(".your-parent-class .non-skin-symptom-choice").attr("id");
}
}
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.
I have the Span Tag with the id attribute having different value inside a loop
like this:
<span class="articlehelp" id="#faqID#"></span>
I have the following jquery declared on dom ready
$('.articlehelp').load('getvoting.cfm?id=' + $('.articlehelp').prop('id'));
But it is loading everytime 1 rather than different id's
The Problem is that the selector for .acticlehelp selects all matching elements, but caling functions on this always takes the first matched element from the collection.
You need to loop over all .articlehelp to achive what you want.
I am not an expert in jquery but something like this may do:
$('.articlehelp').each(function (i, element) {
$(element).load('getvoting.cfm?id=' + $(element).prop('id'));
});
I have two <div> elements, and the following JavaScript code:
var myObject = {
$input: $('<input />'),
insert: function () {
$('div').append(this.$input);
$('div').append(' ');
}
};
myObject.insert();
This, as I expect, produces an <input> element within each of the two <div> elements.
Now when I create a new instance of myObject and call insert() again I will be expecting 4 <input> elements, two in each <div>. Weirdly, I only get 3 <input> elements!
See example code here:
http://jsfiddle.net/FNEax/
You're creating 1 input explicitly:
$input: $('<input />',{value:i}),
...but cloning it implicitly when you try to append it to multiple divs
// 2 divs
$('div').append(this.$input);
Then Object.create doesn't create a new $input, so on the second pass, it appends (moves) the input from the second div (which is actually the original) to the first div, and then does the implicit clone to populate the second.
Here's a jsFiddle example that increments an i variable whenever insert() is called, and adds it as the value of the input. Notice that it is always set at 0.
I also modified it to pass a string to insert so you can see which call each input came from.
The two inputs from the second call both still have the string passed to the first call.
EDIT:
I flipped it around mid explanation, but the concept is the same.
When the second insert() is called, the clone is first created of the original and added to the first div, then the original is appended to the second div (where it already is).
jQuery makes the clones first, then appends the original last.
Here's another jsFiddle example that adds a custom property to the original, then adds some text next to the element with that custom property after each insert(). The text is always added next to that original in the second div.
This is what is happening. From the jQuery docs:
If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned)
If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.
So the first time around, since your input isn't anywhere in the DOM it is cloned and inserted into both divs. But, the second time it is called it is removed from the second div, before being cloned and added back into both divs.
At the end of your code, the first div contains both inputs, but the second div only contains the most recent input, since each input was removed from your last div.
http://jsfiddle.net/hePwM/
Once an element is inserted into the DOM, another .append() call with it as the appended content causes it to move within the DOM (docs). Your code creates a jQuery collection with a single input therein, which input has yet to be appended to the DOM. So the first call to insert() appends it to each (using the cloning or copying mechanism internal to jQ).
In the second call, however, this.$input references something which is already in the DOM (due to the first call). Internally, jQuery is each-ing the collection of DIVs and appending the input which lives inside of this.$input. So it adds it, the moves it.
The primary issue is that you're re-appending the same input over and over. Remember that JavaScript generally references existing objects rather than make new ones. That same input element keeps getting re-referenced.
If you want a method to add an input to every DIV, you should simply pass the input markup into append:
$( 'div' ).append( '<input />' );
The wierd behavior is due to the fact you are using a JQuery collection where you shouldn't be. How it even worked in the first place is beyond my skillset.
var myObject = {
input: '<input />',
insert: function () {
$('div').append(this.input);
//$('div').append(' ');
}
};
try each():
var myObject = {
insert: function () {
$('div').each(function(index) {
$(this).append($('<input />'));
$(this).append(' ');
});
}
};
myObject.insert();
myObject.insert();