I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/
Related
I am trying to add a class to a newly appended DIV without using something like:
t.y.append('<div class="lol'+i+'"></div>');
Here's a better example of what I'm trying to do:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append('<div></div>').addClass('lol'+i);
});
Page load HTML looks like:
<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
<div></div>
<div></div>
<div></div>
</div>
When you append an element through .append, it doesn't change the context of the jQuery object.
You could write it like this:
$('<div></div>').appendTo(t.y).addClass('lol'+i);
or
$('<div></div>').addClass('lol'+i).appendTo(t.y);
(these both do the same thing, simply in different orders, the second possibly being more clear)
the context of the jQuery object will be the newly created div.
t.y.append('<div></div>').addClass('lol'+i);
should be
t.y.append('<div></div>').find('div').addClass('lol'+i);
In the first case you are adding class to the div to which you are appending ..
SO the context is still the parent div and not the newly appended div..
You need to find it first inside the parent and then add the class..
EDIT
If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it..
This will make sure you are not adding the class to all the div's every single time you iterate in the loop..
t.y.append('<div></div>').find('div:last').addClass('lol'+i);
Try this:
t.y.append($('<div></div>').addClass('lol'+i));
Fiddle: http://jsfiddle.net/gromer/QkTdq/
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
var d = $('<div />').addClass('lol' + i);
t.y.append(d);
});
The problem is that append returns the container instead of the thing you just appended to it. I would just do the addClass before the append instead of after:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append($('<div></div>').addClass('lol'+i));
});
EDIT ... or, in other words, exactly what Gromer said. Beat me by five whole minutes, too. I'm getting slow.
You don't mention why you want to number the class attribute to your list items, but in the case that you are actually using them for css don't forget you have :odd and :even css selector attritbutes and also the equivalent odd/even jQuery selectors.
http://www.w3.org/Style/Examples/007/evenodd.en.html
http://api.jquery.com/odd-selector/
I didn't find anything like this. notice the class attribute!
$.each(obj, function (_index, item) {
resultContainer.append($('<li>', {
class: "list-group-item",
value: item.id,
text: item.permitHolderName || item.permitHolderId
}));
});
I need to clone a div and after cloning all the elements within the div should have unique ids. I need to do this using javascript only and not jquery.
Can anyone help me please.
The following code clones an element, uses a recursive function to assign random id's to the cloned element and its children and appends it to the document body. Adjust to your needs. See also this jsfiddle
var someClone = someDiv.clone(true), children = someClone.childNodes;
someClone.id = Math.floor(1000+Math.random()*10000).toString(16);
reId(children);
function reId(nodes){
for (var i=0;i<nodes.length;(i+=1)){
var children = nodes[i].childNodes;
nodes[i].id = Math.floor( 1001+Math.random()*10000 ).toString(16);
if (children.length){
reId(children);
}
}
}
document.body.appendChild(someClone);
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/
I have the following bit of javascript and have tried a number of different ways to get the text from the div with the class dvservicestitle, and any li tags in the div with the dvservicescontent class. Neither work and I'm not sure why. Anyone have an idea what's wrong with this code?
if (html == "") html = "<div class='dvservicestitle'>Our Services</div><div class='dvservicescontent'><ul></ul></div>";
var title = $(html).find(".dvservicestitle");
var elements = $("dvservicescontent li", $(html));
The reason is because the find() method finds children nodes on the current node. Your HTML variable IS the div that you are looking for so the find() method doesn't find it. You need to wrap it in another container.
html = "<div class='dvservicestitle'>Our Services</div><div class='dvservicescontent'><ul></ul></div>";
$(html).find(".dvservicestitle")
>> []
$(html).hasClass("dvservicestitle")
>> true
html = "<div><div class='dvservicestitle'>Our Services</div><div class='dvservicescontent'><ul></ul></div></div>"
$(html).find(".dvservicestitle")
>> [<div class="dvservicestitle">Our Services</div>]
you can use:
var title = $(".dvservicestitle").text();
var elements = $(".dvservicescontent li").text();
.find searches descendants which you don't have. The div to search exists at top level, so it is one of the elements in the jQuery object.
Use .filter to filter the correct element:
$(html).filter(".dvservicestile").text();
var title = $(html).find(".dvservicestitle").html();
var elements = $(html).find('.dvservicescontent ul').children();
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]);