JQUERY change text or value of child element in parent element - javascript

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);

Related

Append values to a specific element in a string with Jquery

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>

How can I remove an element that is NOT on the DOM using jQuery?

I want to use jQuery to manipulate a cloned element that is not on the DOM, to perform actions like .remove() on it. Say I have the following code:
var div= $('<div> <div id="div1"></div> </div>');
div.remove('#div1');
console.log(div.html());
The result on the console will still show that the element was not removed. string manipulation is not desirable, I'm looking for something analogue to $().remove()
The div variable will contain a reference to the outer div. You need to use find() to get the inner div by its id:
var $div = $('<div><div id="div1"></div></div>');
$div.find('#div1').remove();
Using the context argument of the jQuery() function:
$('div', div).remove('#div1');

why is jquery cloning the children element also?

Suppose I have the following code:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Now when I do, $("ul").clone();, it clones the full ul element (all its children also).
I want only to clone <ul> and not its children.
How to do that in jQuery?
I know in pure JavaScript (using cloneNode()), but I can't use this because of additional methods to perform also.
You could empty the element:
$('ul').clone().empty();
There are two problems with the given solutions.
They are unnecessarily inefficient by cloning all children and their data.
They use the native clone, which doesn't clone event handers and other data.
If you want to do a shallow clone with jQuery and transfer all data, detach its contents before the clone operation, then replace them after.
// Fetch the ul and detach its contents
var ul = $("ul");
var contents = ul.contents().detach();
// Do the clone, copying its data
var clone = ul.clone(true);
// Reattach the contents
ul.append(contents);
If there are multiple elements, then do this operation in a loop.
Use .html('') to empty the contents.Try this:
$("ul").clone().html('');
Working Demo
jQuery clone method creates a deep copy of the element.
Description: Create a deep copy of the set of matched elements.
So with jQuery you want be able to get just the ul.
You have two choices:
Empty the object jQuery returns:
$('ul').clone().empty();
Use plain Javascript:
var simpleUl = $($('ul').get(0).cloneNode());

jQuery get result of .insertBefore

My Task:
Insert a Element into the Dom before a specific Element
Return that new inserted Element as a jQuery object
The new inserted Element can not have an Id or anything, the only reliable information to select it is that it was inserted before that other specific Element
Inserting the Element is easy with the .insertBefore method:
var result = $('#myInsertPosition').insertBefore('<div>newInsert</div>');
That gives us a Dom like this:
<div>newInsert</div>
<div id="myInsertPosition"></div>
But result in this case is still the #myInsert Div but I need the newInsert Div.
How can I get the new inserted Div as jQuery object?
Thoughts are with .prev() or other selectors but I can't find a reliable solution.
insertBefore() does return the newly inserted jquery object but your call is backwards, you want to do:
var result = $('<div>newInsert</div>').insertBefore('#myInsertPosition');

Jquery get image HTML

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'))

Categories