Let's say we have the following JavaScript/jQuery code below
function createElement(i, value) {
return $('<div>', { id: "field" + i, text: value});
}
I have a div with an id of "container" and then I do:
var c=$("container");
c.append(createElement(1, "hello, world!");
Now I've got 2 questions
Does the createElement function use jQuery to return an HTML string that gets appended to container or does it dynamically create a DOM element that gets appended to the container?
I'm unfamiliar with this kind of jQuery where you actually create the HTML string (or DOM element) via the $() selector. I tried looking for the documentation on this subject in jQuery's website but I couldn't find it. Can somebody point me in the right direction?
It creates the DOM element on the fly, and appends that.
http://api.jquery.com/jQuery/#jQuery2
In fact it creates the DOM element + it returns a jQuery object which contains your DOM element you just created.
Dogbert was right about this, the doc is here
Related
I'm creating a JQuery object(let's call it $dummyHTML) and setting some html content inside it. Then I go through each of it's child nodes including text ones, do some checks, and append them to a new different JQuery Object(let's call it $refinedHTML).
But the problem is that the contents of $dummyHTML seems to be empty even before I append them to $refinedHTML!
Now, I know that JQuery append function doesn't copy a node, it actually transfers the node to the other JQuery object. So I'm guessing the append function triggers before I mean it to?
Here is a minified example of the issue.
var $dummyHTML = $('<div/>');
$dummyHTML.html('Hello there, <span>myself!</span>');
var $refinedHTML = $('<div/>');
console.log($dummyHTML[0]);
$dummyHTML.contents().each(function() {
$refinedHTML.append($(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But if I remove the .contents part the programs works as expected.
.contents() extracts the content of a DOM element .When you create an object on the fly,it is not yet a DOM element so .contents() will not work however you can manipulate the object data in other ways.
Reference here:
Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements.
I'm using a pretty cool JavaScript/jQuery library called OpenSeaDragon. It's for displaying deep zoom images. It also have a method for adding 'overlays', essentially creating a div and putting it over the image with coordinates though a viewer object. There's also a method for removing the overlays: https://openseadragon.github.io/docs/OpenSeadragon.Viewer.html#removeOverlay
viewer.removeOverlay(element or element id);
As the doc states regarding the input param: "A reference to the element or an element id which represent the ovelay content to be removed." I'm creating a whole bunch of overlays -- creating a grid out of rectangles -- so I've given them a class. Passing the class to this method doesn't work. So I'm trying to understand what they mean by "element". Is there a way I can use JQuery or JavaScript to select an "element" and pass it to the method? Or some such thing?
thanks
It usually means an element in your document, i.e. a DOM node. So, a div, or a span, or somesuch.
You can select an element with jQuery pretty easily:
var $obj = $('#elementId');
and then grab the underlying DOM node from the jQuery object that results:
var elm = $obj[0];
Thanks everyone. Here's how to do it:
var n = $(".gridcell").length
for(i=0; i<n; i++) {
viewer.removeOverlay($(".gridcell")[0]);
}
At first I though I could iterate through the array, calling removeOverlay() on each item index successively. This was causing half the overlays to be deleted on each run. So, for 16 overlay, I have to run it 4 times. After a few minutes it clicked... Each time you get the elements $(".gridcell"), it returns a new array.
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.
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.