Insert node between two nodes based on attribute condition? - javascript

i was wondering if there's a jquery (or some other library) function that allows me to insert a node (div) between two other nodes (divs) based on its attribute.
For example:
Lets say i have this html code:
<div value=111/>
<div value=222/>
<div value=444/>
i want to insert <div value=333/> between the 222 and 444 accordingly.
Thanks to all helpers.

Yes you can do this.
obtain desired div using querySelector
use after method to add new element after the one obtained in the previous step
const div = document.createElement('div');
div.textContent = 'three';
const target = document.querySelector('div[value=two]');
target.after(div);
<div value="one">one</div>
<div value="two">two</div>
<div value="three">four</div>
To dynamically the find correct spot, you can use find method like this.
find the first element with value bigger than the one you provide
use before method to place the new element before the one from the previous step
const myValue = 333;
const div = document.createElement('div');
div.textContent = myValue;
const target = [...document.querySelectorAll('div')]
.find(v => Number(v.getAttribute('value')) > myValue );
target.before(div);
<div value="111">111</div>
<div value="222">222</div>
<div value="444">444</div>

use after();
here is working example in codepen
https://codepen.io/anon/pen/BVjbqZ

Both jQuery offers a variety of methods for this: insertBefore, insertAfter, before, and after.
The DOM provides insertBefore and insertAdjacentHTML.
For instance, using jQuery's before:
$("div[value=444]").before("<div value=333></div>");
Or using the DOM's insertBefore:
var div = document.createElement("div");
div.setAttribute("value", "333");
var target = document.querySelector("div[value=444]");
target.parentNode.insertBefore(div, target);
Or using the DOM's insertAdjacentHTML:
document.querySelector("div[value=444]").insertAdjacentHTML(
"beforebegin",
"<div value=333></div>"
);
Side note: div is not a void element, <div /> isn't a self-closing tag, it's a start tag with a / in it that's ignored.
Side note 2: value is not a valid attribute for div elements.

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>

Append an element inside a specific div's element using Javascript

I know how to append an element inside another element, but how do I specify which class I want to append it to?
For example:
<div class="main" id="11">
<div class="somethingelse>
<div class="moreThings">
/*How to append to this class?*/
</div>
<div class="extraThings">
</div>
</div>
</div>
What I have is something like this:
var x = document.createElement("IMG");
x.setAttribute("src", "../truck.png");
document.getElementById(order_id).appendChild(x);
document.getElementById("btn_transport_"+order_id).style.display = "none";
There could be hundreds of classes with same name which is why I need to define them by id.
At the moment I am appending the img under everything other divs, but I would like to append it inside "morethings". How would I do that?
You could do something like this:
document.getElementById(order_id).getElementsByClassName("moreThings")[0].appendChild(x);
Make sure getElementsByClassName("moreThings") returns at least one element.
You can find out more about getElementsByClassName(...) from HERE. The gist of it is:
Returns an array-like object of all child elements which have all of the given class names
You could use document.querySelector. It allows CSS-like selectors. In your case it could look like
const myElementToAppendTo = document.querySelector('#myID .morethings');
myElementToAppendTo.appendChild(x);

Moving the content of a DIV to another DIV with jQuery

http://www.frostjedi.com/terra/scripts/demo/jquery02.html
According to this link elements can be moved around by doing $('#container1').append($('#container2')). Unfortunately, it doesn't seem to be working for me. Any ideas?
See jsfiddle http://jsfiddle.net/Tu7Nc/1/
You must append not your div exactly, but your div's content(inner HTML) with Jquery's html() function.
HTML:
<div id="1">aaa</div>
<div id="2">bbb</div>​
Jquery:
$("#1").append($("#2").html());
Result:
aaabbb
bbb
It is best not to use html().
I ran into some issues due to html interpreting the contents as a string instead of a DOM node.
Use contents instead and your other scripts should not break due to broken references.
I needed to nest the contents of a DIV into a child of itself, here is how I did it.
example:
<div id="xy">
<span>contents</span>
</div>
<script>
contents = $("#xy").contents(); //reference the contents of id xy
$("#xy").append('<div class="test-class" />'); //create div with class test-class inside id xy
$("#xy").find(">.test-class").append(contents); //find direct child of xy with class test-class and move contents to new div
</script>
[EDIT]
The previous example works but here is a cleaner and more efficient example:
<script>
var content = $("#xy").contents(); //find element
var wrapper = $('<div style="border: 1px solid #000;"/>'); //create wrapper element
content.after(wrapper); //insert wrapper after found element
wrapper.append(content); //move element into wrapper
</script>
To move contents of a div (id=container2) to another div (id=container1) with jquery.
$('#container2').contents().appendTo('#container1');
You can also do:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) el1.appendChild(el2);
or as one statement, but not nearly as robust:
document.getElementById('container1').appendChild(document.getElementById('container2'));
Edit
On reflection (several years later…) it seems the intention is to move the content of one div to another. So the following does that in plain JS:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) {
while (el2.firstChild) el1.appendChild(el2.firstChild);
}
// Remove el2 if required
el2.parentNode.removeChild(el2);
This has the benefit of retaining any dynamically added listeners on descendants of el2 that solutions using innerHTML will strip away.
$('#container1').append($('#container2').html())
Well, this one could be an alternative if you want to Append:
document.getElementById("div2").innerHTML=document.getElementById("div2").innerHTML+document.getElementById("div1").innerHTML
if you wanted to rewrite contents:
document.getElementById("div2").innerHTML=document.getElementById("div1").innerHTML
I suggest a general approach with a function and jQuery:
function MoveContent(destId, srcId) {
$('#' + destId).append($('#' + srcId).contents().detach());
}
Content of a detached source node is appended to a destination node with call:
MoveContent('dest','src');
The first parameter is an id of a new parent node (destination), the second is an id of an old parent node (source).
Please see an example at: http://jsfiddle.net/dukrjzne/3/

Add text before or after an HTML element

If i have an HTML element like <div> with some text inside or another elements can I add before or after this div some text data without an html element, just plain text?
I'd like to use only pure Javascript.
Something like :
<div id="parentDiv">
my text must be added here
<div id="childDiv"></div>
</div>
Yes, you can create a text node with document.createTextNode('the text')
Then you can insert it like an element, with appendChild or insertBefore.
Example that insert a text before #childDiv:
var text = document.createTextNode('the text');
var child = document.getElementById('childDiv');
child.parentNode.insertBefore(text, child);
Just for the record:
div.insertAdjacentHTML( 'beforeBegin', yourText );
where div is your child-DIV.
Live demo: http://jsfiddle.net/ZkzDk/
If you just need text, I find that element.insertAdjacentText(position, text) is flexible for many scenarios and is also compatible with older browsers like IE6. Where position is exactly where you want the text to be and text is the text node or just a string. The options are:
'beforebegin' Before the element itself.
'afterbegin' Just inside the element, before its first child.
'beforeend' Just inside the element, after its last child.
'afterend' After the element itself.
Like this:
let div = document.getElementById('parentDiv');
div.insertAdjacentText('afterbegin', 'My Plain Text..');
In regards to the topic and the users question for inserting before or after, here is an example for after:
var text = document.createTextNode("my text must be added here.");
var childTag = document.getElementById("childDiv");
childTag.parentNode.insertBefore(text, childTag.nextSibling);
If the childTag does not have any siblings, it is okay because the insertBefore method handles this case and simply adds it as the last child.
Also can possibly use the appendChild() method after creating text node then add your childTag via the parentNode.
You can add text node. Create node - document.createTextNode('text') and then insert/append/replace - do whatever you want.
Something like this should do it:
<script type="text/javascript">
var parent = document.getElementById('parentDiv');
var sibling = document.getElementById('childDiv');
var text = document.createTextNode('new text');
parent.insertBefore(text, sibling);
</script>

Adding HTML elements with JavaScript

So, if I have HTML like this:
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
How can I use JavaScript to add an HTML element where that blank line is?
node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');
Available Options
beforebegin, afterbegin, beforeend, afterend
As you didn't mention any use of javascript libraries (like jquery, dojo), here's something Pure javascript.
var txt = document.createTextNode(" This text was added to the DIV.");
var parent = document.getElementById('div');
parent.insertBefore(txt, parent.lastChild);
or
var link = document.createElement('a');
link.setAttribute('href', 'mypage.htm');
var parent = document.getElementById('div');
parent.insertAfter(link, parent.firstChild);
Instead of dealing with the <div>'s children, like other answers, if you know you always want to insert after the <a> element, give it an ID, and then you can insert relative to its siblings:
<div id="div">
<a id="div_link">Link</a>
<span>text</span>
</div>
And then insert your new element directly after that element:
var el = document.createElement(element_type); // where element_type is the tag name you want to insert
// ... set element properties as necessary
var div = document.getElementById('div');
var div_link = document.getElementById('div_link');
var next_sib = div_link.nextSibling;
if (next_sib)
{
// if the div_link has another element following it within the link, insert
// before that following element
div.insertBefore(el, next_sib);
}
else
{
// otherwise, the link is the last element in your div,
// so just append to the end of the div
div.appendChild(el);
}
This will allow you to always guarantee your new element follows the link.
If you want to use something like jQuery you can do something like this:
$('#div a').after("Your html element");
jQuery has a nice, built in function for this: after(), at http://api.jquery.com/after/
In your case, you will probably want a selector like this:
$('#div a').after('<p>html element to add</p>');
The code examples from the link given above also show how to load jQuery if that is new to you.
Element#after can be used to insert elements directly after a certain HTML element.
For example:
document.querySelector("#div > a").after(
Object.assign(document.createElement('div'), {textContent: 'test', style: 'border: 1px solid'}));
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
Assuming that you are only adding one element:
document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);

Categories