How can I copy the whole <img /> using jquery.
At the moment I am trying: $('img').clone().html()
Usage:
'<div class="content-left">'+$(this).find(".bar .info").html()+$(this).find(".bar img").clone().html()+'</div>';
To create new copies of every image in the DOM you can select them and clone them, then append them to some container.
//store a clone of all the images in the DOM in a variable
var $clone = $('img').clone();
//now add the clones to the DOM
$('#newContainer').html($clone);
Here is a demo: http://jsfiddle.net/jasper/r3RDx/1/
Update
You can create your HTML like this:
//create a new element to add to the DOM
//start by creating a `<div>` element with the `.content-left` class
//then add a string of HTML to this element
//then append a set of DOM elements (clones) to the same parent element (the `<div>`)
var $newElement = $('<div />').addClass('content-left').html($(this).find('.bar .info').html()).append($(this).find('.bar img').clone());
//then you can add the new element(s) to the DOM
$newElement.appendTo('#newContainer');
Here is a demo: http://jsfiddle.net/jasper/r3RDx/2/
jQuery objects are simple arrays containing the html of the selected element. This means that I can simply do: $('img.someclass')[0] to access the html of the first (and probably only) matched element.
clone includes the event handlers of the object. If you want just the html whats below would be fine
$('#someid').html($('img'))
Related
I have an element in local storage with multiple elements, for simplicity, I will make the element:
<div id="outer">
<ul id="inner">
<li id="item">
</li>
</ul>
</div>
The element is saved as a string and I want to manipulate the contents.
Like such:
let local_storage_element = localStorage.getItem("val")
$(local_storage_element+':last-child').append("<p>something</p>")
No matter what selector I add after local_storage_element it will always append the value to the string not to the selected element(:last-child in this case)
does anyone know how to append to a specific element within the string??
Although you have written jquery in the title there is a javascript tag added also so I thought why not provide an answer that justifies your needs and helps you accomplish the task in the same way you want.
The
DocumentFragment interface represents a minimal document object that has no parent. It
is used as a lightweight version of Document that stores a segment of
a document structure comprised of nodes just like a standard document.
The key difference is that because the document fragment isn't part of
the active document tree structure, changes made to the fragment don't
affect the document, cause reflow, or incur any performance impact
that can occur when changes are made.
So how to do it as the DocumentFragment still appends node with it and not string, we will create a temp element and add the HTML from the localStorage using innerHtml and then append the firstChild of that temp node i.e our actual string which is now treated as a node, to the document fragment and then search and appends HTML to it, we will use our temp element to add HTML every time see below.
I will append a new child div to the element #outer in the string given above in the post here is the working FIDDLE as SO does not support localStorage you can see it working there open the console to view the resulting HTML with the new child added and below is the code
$(document).ready(function () {
if (localStorage.getItem('html') === null) {
localStorage.setItem('html', '<div id="outer"><ul id="inner"><li id="item"></i></ul></div>');
}
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = localStorage.getItem('html');
frag.appendChild(temp.firstChild);
temp.innerHTML = '<div class="new-child"></div>'
frag.querySelector("#outer").appendChild(temp.firstChild);
console.log(frag.querySelector("#outer"));
localStorage.removeItem('html');
});
You can't use string as selector. If you want transform string to html then you should put it in some element as innerHTML. So try create some hidden div and insert your string as HTML to it. Something like this
var your_string = '<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul>';
document.querySelector('.hidden').innerHTML = your_string;
document.querySelector('ul li:last-child').innerHTML = 'your content';
document.querySelector('.result').appendChild(document.querySelector('ul'));
Example
The problem may arise when you get '<div id="outer">' from localStorage to use it as a selector since it only accepts "#outer" to be a selector. If you want to add an element to be the last child of parent's element, you could use after() instead of append().
$(document).ready(() => {
if ($("#charl").children().length === 0)
{
// if using after with no element inside ul then it will be inserted after il
$("#charl").html("<li>foo</li>")
}
else {
$("#charl li").after("<li>bar</li>")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="charl">
<li>Foo</li>
</ul>
I make some code width jquery My goal is add lists under the #pivot and above <li>bottom</li> How to do??
When I tried like this the only <li></li> added without text "new row"
Please teach me
HTML
<li>top</li>
<li id="pivot">Pivot</li>
<li>bottom</li>
Javascript
var dom = '<li></li>';
$('a',dom).text('new row');
$('#pivot').after(dom);
That's because you are creating a jQuery object from a string but you don't store/use the created elements.
$(dom) // parse the string and create a jQuery object
.find('a') // find the `a` descendants
.text('new row') // update their textContent
.end() // get the previous jQuery collection
.insertAfter('#pivot'); // insert the collection after `#pivot` element
dom is not a live node. It is just string..
If you create a jquery object out of it first, it will work
var dom = $('<li></li>');
$('a',dom).text('new row');
$('#pivot').after(dom);
I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});
I have a variable with a jQuery object, for example:
var div = $('#div_element');
How can I manipulate ONLY the div variable, without changing the #div_element itself?
I want to do some edits on the div variable and to pass it as an argument to a plugin, like this:
var el = $('#div');
el.find(':first').remove();
$().popup(el); //I wrote this plugin myself
Actually I want to display popup containing the #div element (with removed the first "child"), but don't want to change the #div element itself.
Use clone to create a copy of the element.
var el = $('#div').clone();
You can use like
$().popup($("#div :not(:first-child)"));
I have HTML in a JavaScript string (containing usual, nested HTML). Using jQuery, can I convert that into a valid HTML element in a single stroke using any of the document.create* functions? My requirement is to use document.getElementById on the created DOM object.
Take simple nested example.
var dom_string = '<div>xxx<div>yyy</div></div>';
create HTML DOM elements using $() function of jquery and append wherever you want.
i have taken 'body' but you can append anywhere.
$(dom_string).appendTo('body');
Alternatively you can implement this with pure javascript:
var dom_target = document.getElementById("target");
dom_target.innerHTML = dom_string;
Create a dummy element and set its innerHTML to your HTML string.
// Construct a container as a placeholder for your content
var container = document.createElement('div');
container.id = 'container';
// Inject the container into the DOM
document.body.appendChild(container);
// Populate the injected container with your content
container.innerHtml = '<p id="pTag">I am a <em>P</em> tag with some <strong>nested markup</strong>.</p>';
To convert Html text into a Jquery-Object use the $() function:
div = '<div>hello world</div>';
$div = $(div);
But as others have noted in most cases you don't need that because DOM manipulation functions like append() and prepend() will accept plain text, so
$('body').append('<div>hello world</div>');
is absolutely fine.