How to find and remove attributes in cloned item using jQuery? - javascript

I trying to clone a div content with below code.
var clonedItem = $("#cloneableSchoolTab").clone();
clonedItem.find(".clonableSchool").addClass("clonedSchoolTab" + schoolTabCount );
$("#clonedSchoolTabsContainer").append(clonedItem);
First line gets the whole target item. But, the excecution of second line, the value of clonedItem changed as empty array. I dont know. If i merge the first 2 line, the reasult was same as the above code.
HTML Code:
<div id="cloneableSchoolTab" class="schoolInput">
<input type="text" id="schName"/>
<input type="text" id="schDes"/>
</div>
Any help would be appreciative.
Thanks in advance

Can you post some HTML code, so that we can see what are the elements the above code is trying to clone, the only thing that I can see is if the find() method fails to find an element with class name ".clonableSchool" then it is constructing an empty jQuery object, as the jQuery doc says:
the .find() method allows us to search
through the descendants of these
elements in the DOM tree and construct
a new jQuery object from the matching
elements
Note: I believe it should be a comment not an answer, but I don't have that privilege yet, sorry.

Related

Change Class Name of a div in Jquery after find()

I have a brief quesiton about the nautre of jquery.
I tried to change the class name of an element using Jquery by using the argument below.
var classman=$('body').find('div')[2].className('anything')
body has several different divs and I picked the third one by
using .find('div')[2].
When I logged it, .find() argument spits out the whole html line
and I checked the type of it and console says it's "object"
So I was expecting I could access tot he element by typing like
classman.class
but neither the first approach nor the second approach didn't worked out. What should I do to change the second element and the change the class?
Thank you in advance.
I'm not a heavy user of Jquery but Just curious about it and wanted to know how to do it as a basic knowledge.
To add a class in jquery you can do this as follows:
$('body').find('div').addClass('name')
console.log($('body').find('div').attr('class'))
<body>
<div class="test">
</div>
</body>
To get the classes of an element we use attr ('class') in jquery.
In your example you said you wanted to take the second element, to do this use the method eq, (eq. (1))
Example:
$('body').find('div').eq(1) // Get second element

Angularjs: How to check if element's children contains certain element (by ID)

<div id="divWrapper">
<input id="firstInput"/>
<div id="insideDiv">
<input id="secondInput"/>
</div>
</div>
This is the basic structure of my HTML. So, given an access to "divWrapper" element how do I check if it contains "secondInput".
NOTE: This is to be done without jQuery. Only using Angularjs utility functions.
UPDATE: The solution should be dynamic. Meaning it should find any child, how much ever down the level it is in the DOM tree.
UPDATE 2: Please don't get misguided by "input" element. I don't want to track the text inside it. I want to a logic which will check if me or any of my child is clicked. If NOT then hide myself and my children.
var secondInput = angular.element(document.querySelector("#divWrapper #insideDiv #secondInput"));
This will return the element you're looking for or empty if it doesn't find anything.
angular.element("#someId").find("someOtherSelector") already does exactly what you want.
So for your question you could just do...
angular.element("#divWrapper").find("#secondInput"); // Empty array OR a match

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.

Remove elements from in memory element in js

I have a java script file that is used in several places. It has this code:
var newDiv = lastDiv.cloneNode(true);
lastDiv has some <input> elements that I do not want to clone. I've created these input elements with the attribute <input copy="dont"> so that I could remove them out using the following code:
newDiv.select("input[copy=dont]").remove()
The prototype.js select() finds these elements. But remove() does not work, newDiv still has the input elements that I wanted filtered. Prototype documentation states that it will remove from the document, but newDiv is not in the document, it is only in memory.
This is solved now: select() was returning an array. If only prototype would have returned a meaningful error message. It was returning the list of matching elements. Thanks for your answers guys. Will use valid HTML5. This works now
newDiv.select("input[copy=dont]")[0].remove()
i think it's just a type in your selector , try this:
newDiv.select("input[copy='dont']").remove()
also , just s suggestion , use the attribute data-copy instead of copy ex.
<input data-copy="dont" type="text" />
this will keep your elements valid HTML5

Removing last cloned element

Similar to this thread, I am trying to be able to add and remove select boxes for different parts of my document. However, when I call the remove function, it removes the first instance of my cloned object, instead of the last. I have tried using :last and :last-child, but they do not seem to be working(May just be a syntax error, as I am new to Javascript/Jquery)
Also, should I be assigning different id's to each of my cloned objects? My goal is for each g:select to select a database object, and compile all of the different objects text into 1 big string (each object has a 'documentBody' field that I want to compile). Since I am basically doing the same thing to each object, is it necessary for me to assign specific id's to each select, or will just cloning them be sufficient?
Here is what I currently have implemented
<div id="selects">
<g:select name="intro"
id= "intro" from="${package.name.Subtag.findAllWhere(tag: package.name.Tag.get(2))}" noSelection="['': 'Please choose Subtag']"/>
</div>
<button onclick="addSelect()">Add</button>
<button onclick="removeSelect(intro)">Remove</button>
and
<g:javascript library="jquery"/>
<g:javascript>
function addSelect(){
var cloner = $("#intro").clone();
$("#selects").append(cloner);
}
function removeSelect(id){
$("#intro:last-child").remove();
}
</g:javascript>
As Jai has mentioned, the issue is that you are cloning and appending an element with an id, creating a duplicate id on the page. When jQuery searches for an element by id, it stops at the first one found, regardless of any other pseudo classes.
The issue is that a duplicate id on the page means that the HTML document is invalid, so all bets are off. Older browsers may even throw an error. Using a class rather than an id prevents the .clone() function from copying the dupe id, but if you still need the first element's id, you can always remove it from your cloned object before appending it to the page:
cloner.removeAttr('id');

Categories

Resources