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.
Related
Using jQuery I am trying to select an element that has a unique id. I need to check the length of the returned jquery object to see if the element is there on the page.
if i write:
$('#main-content').length
i get 0. Strangely, the element is there. Instead, if i write:
$('main#main-content').length
i am getting 1.
I thought i need not specify the element before the selector. Any idea why this is happening?
An iframe is basically a separate document from the parent. So searching the parent will not find elements from the iframe.
However, this should work
$(document).ready(function(){
var iFrameEl = $("iframe#frameID").contents();
iFrameEl.find("#main-content").addClass('test');
});
I have a hidden textbox with id in the form of a part of a collection. I use the ID in this way so as to have them bind to my model. This is the simplified version of my code.
<input id="Model.Bed[0].Id" name="Model.Bed[0].Id" type="hidden" value="bed1">
I am using Jquery to remove it but while it does not throw any error, it does not get deleted. This is my code.
$('#Model.Bed[0].Id').remove();
Am I missing something?
Your jQuery selector returns 0 items because it is an invalid selector expression( [ has a different meaning)
Try the name selector. This should work
$("[name='Model.Bed[0].Id']").remove();
Keep in mind that it is allowed to have more than one element with same name attribute value. So use based on your DOM.
Also, If you have this input element generated in a loop and you have some button inside this loop for executing your remove code, you should consider using relative selectors. closest() and find() methods are handy in this case.
For example,
// Register click event with element with css class "someDeleteBtn"
$(".someDeleteBtn").click(function(e){
e.preventDefault();
$(this).closest(".containerDiv") //get to outside container
.find(".myHdnBed") // find the hidden input with this css class
.remove(); // remove
});
To escape special characters in an ID selector, you can use \ like so:
$('#Model\\.Bed\\[0\\]\\.Id').remove();
which works: http://codepen.io/anon/pen/XpqJxV
Read more here: https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/
In the end though, you really shouldn't have a value like that as an ID in the first place.
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
So, I know how to create an element in jQuery in various ways. But I've never come across this before today:
var myspacer = $('<div />', {
"id": "nav-spacer",
"height": mynav.outerHeight()
});
Later on in the code, this variable is added to the DOM with jQuery's .before() method. Can somebody explain what's going on here? What kind of object is being created? How does jQuery know how to turn this into an HTML element?
That is the $( html, props ) syntax of the jQuery() function - it is explained quite clearly in the API documentation:
html A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).
props An map of attributes, events, and methods to call on the newly-created element.
If the function determines that the first parameter is a string that looks like an html snippet it creates a new element (or elements) from that snippet. If you pass a map in the second parameter it creates the specified attributes on the newly created element.
The new element is not automatically added to the document, but you seem to already have seen that since you mention the .before() code that does add it.
According to jQuery $( html, properties) syntax, above code creating a div with id="nav-spacer" and height supplied by mynav.outerHeight() method without any content as jQuery object but not added to DOM.
In $( html, properties), html is string and properties is collection of attributes/event and so on.
An alternative approach may be:
var myspacer = $('<div id="nav-spacer" height="'+ mynav.outerHeight() +'"></div>');
But your one is more readable and efficient.
Using .before() method myspacer is added to DOM just before the selector passed within .before() as param. Example:
myspacer.before('div.hello');
Will add myspacer before the div with class=hello like:
<div id="nav-spacer" height="some_value"></div>
<div class="hello"></div>
jQuery creates a new element if you pass in HTML like $('<div/>') because it's smart. :P It recognizes that the string is HTML (rather than a selector) and treats it differently. See the docs.
The new element is created but not added to the DOM until you add it yourself, eg. with appendTo().
From the documentation: "To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag."
Edit: I stand corrected, you can write $('<div/>') without an explicit closing tag. This works as long as the HTML doesn't contain nested elements (of course). See the other examples from the docs:
// With nested elements and closing tags - HTML must be well formed
$("<div><p>Hello</p></div>").appendTo("body");
// Without closing tag - HTML is still well formed
$("<div/>", {
"class": "test",
text: "Click me!",
click: function(){
$(this).toggleClass("test");
}
}).appendTo("body");
Similar questions:
jQuery document.createElement equivalent?
Creating a div element in jQuery
What is the most efficient way to create HTML elements using jQuery?
http://api.jquery.com/jQuery/#jQuery2
This should give you the explanation you're looking for =D.
To summarize, it's a quick JQuery on-the-fly element creation method.
I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/2/
You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from
iframediv.innerHTML = iframe;
to
iframediv.appendChild(iframe);
Edit to actually answer your question:
Your variable iframe is a reference to a DOM element. It's object representation is an <iframe> element while its textual representation is simply [object HTMLIFrameElement].
By using innerHTML you are attempting to insert its textual representation into the DOM. This is just how the method works. You may come across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g.
element.innerHTML = '<div>some text</div>';
In this case the browser will correctly add a <div> node as a child of element.
For your <iframe> element to be inserted into the DOM using the variable iframe, you must use the appendChild method which will add the IFrame object as a child node to iframediv.
$('#iframecontainer').append(iframe);
instead of
var iframediv = document.getElementById('iframecontainer');
iframediv.innerHTML = iframe;
should fix the problem
var new_iframe = $("<iframe></iframe>");
new_iframe.appendTo($("#div_to_insert_into"));
The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div or an iframe that has access to all of jQuery's awesome methods... like .append() and .click().
Generally speaking, jQuery's real purpose is to turn lines of code like
var iframediv = document.getElementById('iframecontainer');
...into ...
var iframediv = $("#iframecontainer");
...which you can then use to do with whatever you please, like
iframediv.appendTo("#anotherDiv");
Good luck.