Select element inside a cloned element variable - javascript

I have cloned an element using clone():
var clone = $('#orig').clone();
The clone works fine, but I having some trouble trying to select elements inside it by ID.
All nested elements have the same ID as the original ones, and I need to manipulate some before appending them to the page...
I am trying something like this for example:
alert(clone.filter("#Full").attr('id'));
Could you help me on that?

The snippet you provided in your question works fine!
Just replace filter with find.
See this fiddle: http://jsfiddle.net/Pkv7S/
However, yes, you should be wary of duplicate IDs.

Try this way
var clone = $('#orig').clone();
clone.attr('id','orig1');
check it here http://jsfiddle.net/3tWks/

Firstly, use classes instead of IDs. IDs should always be unique within a document, and may result in unpredictable behaviour if cloned (if you want the cloned elements to have IDs, by all means assign new ones when you clone!)
That said, you want to be using .find instead of .filter to find elements nested within your clone element:
clone.find(".myClassName")
/* or */
clone.find("#Full")
.find – jQuery Docs

Related

How to append to a variable in jquery?

I have the following code:
var golden_site = '<div id="golden_site"></div>';
$('.form_content').append(golden_site);
var lookup = '<input type="text" name="lookup" value="test">';
Why is this not working:
$(golden_site).append(lookup);
But accessing the node by id works:
$('#golden_site').append(lookup);
This $('#golden_site') selects the div with id=golden_site. While this $(golden_site) doesn't select anything.
Taken from here, you have the following ways of selecting an element using jQuery
Selecting Elements by ID
Selecting Elements by Class Name
Selecting Elements by Attribute
Selecting Elements by Compound CSS Selector
Pseudo-Selectors
The way you tried to select your div doesn't follow one of the above ways. Hence you didn't make it. While using the id you made it, since this is included in the above ways.
update
As Guffa pointed out (I didn't now it) in his comment,
The call $(golden_site) doesn't try to use the string as a selector at
all. It will create an elements from the HTML string, and actually
return that element
The code is working fine, but it doesn't do what you think.
The $(golden_site) part will create a new div element from the HTML code in the string. The lookup element will then be appended to that div. As the div is an element that you just created, it's not in the page and the lookup element that you appended to it isn't in the page either.
If you create the div element first and then append that to the page, instead of using a string in the append, then you have a reference to the div element:
var golden_site = '<div id="golden_site"></div>';
var element = $(golden_site);
$('.form_content').append(element);
Now you can append things to it:
element.append(lookup);
Because when you say
$(golden_site).append(lookup);
Actually you mean:
'<div id="golden_site"></div>'
In plain words, it's just a string, not a jQuery object that can be appended to. golden_site is just a string.
The reason is because the $() is in fact a wrapper of jQuery over the document.querySelector(). So as expected both methods should behave similar, when you do:
$("#blah").append(x);
Indeed the browser is doing this:
document.querySelector("#blah").appendChild(x);
So both methods should work as they explain here -> How query Selector works
As you can see the variable passed as argument is a string that will be used as a CSS Selector, they explain here -> CSS Selector List
I will add this graphic with some of the most common ways to select elements from the DOM, don't forget the '', courtesy from W3CSchools.

return a single html element with jquery

How can I get jQuery to return a html element exactly the way that getElementById does?
if I console.log($('#container')) I will get :
[<div id="container"></div>]
But the API I am interacting with obviously doesn't want that (an array) - it wants :
<div id="container"></div>
I know I can achieve this with $('#container').get(0) and a few other ways, It just seems overkill - especially as I'm selecting an ID which will always be unique.
What am I missing guys?
Thanks
If you just want a single DOM element, then just use plain javascript:
var obj = document.getElementById("container");
jQuery selectors always create a jQuery object with an array of elements in it. That's just the way it's designed. If you want a single element, you either get the first element out of the jQuery object or you use a different tool.
From a jQuery object, you can get the first object either with:
$('#container').get(0)
or with:
$('#container')[0]
But, I would argue that both are more than you need if all you want is the single object that has an id. Just use document.getElementById(). If you want less typing, you could make your own short function:
function $$(id) {
return(document.getElementById(id));
}
var obj = $$("container");
try using .html() it will return the html of the element your selecting see:
http://api.jquery.com/html/

How to add child tags to a javascript array

I'm trying to fill an array with all direct child elements of a div.
example:
<div>
<span></span>
<a></a>
</div>
should result in an array containing span and a
How Would I achieve this?
I tried var elements = $('.thediv').children(); but that doesn't seem to work.
Also how Would I then use that information for this kind of function?:
$("element1","element2","element3") depending on the result of the array?
Really thank you for your help! I am kind of lost with this thing
Note: I'm using zepto.js which has a similar syntax to jquery but misses a lot of functions so that might be a problem but I am also happy with solutions using jquery syntax because it should work pretty well :) https://github.com/madrobby/zepto
To get the tags into the array, you could easily use, with jQuery (though I'm unfamiliar with zepto):
var elementsArray = [];
$('div').children().each(
function(i){
elementsArray.push(this.tagName.toLowerCase());
});
JS Fiddle demo.
And to use them, you can try:
for(i=0;i<elementsArray.length;i++){
$('div').find(elementsArray[i]).css('color','red');
}
JS Fiddle demo.
Although this simply uses the tagName of each element, so if there is more than one a within the relevant element all elements matching the selector, effectively $('div').find('a') in this case, will be targeted by the selector.
The above caution seems to be discounted through use of a more complicated selector, and behaviour, and allows for each element to be iterated over one at a time, though I can't help but feel it's a little more complex than it needs to be:
var elementsArray = [];
$('div').children().each(
function(i){
elementsArray.push(this.tagName.toLowerCase());
});
for(i=0;i<elementsArray.length;i++){
$('div')
.find(elementsArray[i])
.not('.edited')
.eq(0).css('color','red')
.addClass('edited');
}
JS Fiddle demo.
Sigh, I'm an idiot. The final iteration of this is below, which reduces the complexity somewhat, and allows for proper iteration over each element according to their position in the array:
var elementsArray = [];
$('div').children().each(
function(i){
elementsArray.push(this.tagName.toLowerCase());
});
for(i=0;i<elementsArray.length;i++){
$('div')
.children()
.eq(i)
.css('color','red');
}
JS Fiddle demo.
Having said the above, though, if you want to "target all elements within," why not simply target those elements with:
$('div').children();
Which will select, and target, each direct child of the div element without first holding them in, or having to hold them in, a user-created array variable.
$("div").children().toArray();
http://api.jquery.com/toArray/
$("element1","element2","element3")
Does this mean you want to use the array as a jQuery selector? Or you really want the tag names?
Each DOM node has a childNodes attribute, which is a NodeList containing all the direct descendants of the node in question.

Javascript Clonenode() - get element by id?

I am fiddling with this javascript code here
http://jsfiddle.net/7Sd4W/4/
I am trying to get it to clone a select element with ID = "sel0"
Then when It clones it I want it to create the same select element but with "sel+i" , i increments meaning everytime its cloned
The ids would be sel0,sel1,sel2,sel3,sel4 etc..
I tried changing
document.getelementsbyID()
or
document.getelementsbyname()
However it does not seem to work
Thanks
var copy = orig.cloneNode(true);
copy.setAttribute("id", modify(orig.getAttribute("id")));
document.body.appendChild(el)
getElementsByTagName works. You can also assign a unique ID to the node before appending it (duplicate IDs can cause all kinds of issues):
See http://jsfiddle.net/7Sd4W/9/

JQuery remove images

I'm curious if anyone knows why this piece of jQuery code doesn't remove the images?
var a = $('#tblMain').clone().remove('img');
The table is being selected. This is trying to take the table on the webpage and export to excel but I do not want the images to export.
Thank you,
Do it like this:
$("#tblMain").clone().find("img").remove();
EDIT: Okay, here's the problem:
selector: A selector expression that
filters the set of matched elements to
be removed.
http://api.jquery.com/remove/
The img in .remove('img') is to filter the set of items in the jquery object, NOT to find elements within the items themselves. In this case, the jquery object contains only one item, the cloned table. Therefore, .remove('img') removes nothing, since the jquery object does not contain any images (only images within items it contains).
I don't know what's happening behind the scenes, but you're referring to some variable called img whilst you most probably just want to select all img elements. In that case, you ought to use a selector as a string:
var a = $('#tblMain').clone().remove('img');
EDIT: .clone.remove does not seem to work indeed. I used this workaround which actually works:
.find('img').each(function() {$(this).remove()});

Categories

Resources