How to append content to querySelectorAll element with innerHTML/innerText? - javascript

I currently have my class element:
var frame_2 = document.querySelectorAll(".name");
Currently this div is empty. I now want to "append/add" some content to that div - I had a go with innerHTML + innerText but for some reason nothing seems to be added.
Example:
frame_2.innerHTML = '<img src="image.gif" />';
and
frame_2.innerText = 'some text';
Any suggestions? Im not sure if there are ways of doing the same - or performance'wise something better?

this gives you a list of elements that contain the class name
var name=document.querySelectorAll(".name");
you want the first element?
name[0].textContent='some text';
This gives you one single element, the first one.
var name=document.querySelector(".name");
name.textContent='some text';
To append stuff
name.appendChild(document.createTextNode('pizza'));
name.appendChild(document.createElement('div')).textContent='spaghetti';
name.appendChild(document.createElement('img')).src='cookie.jpg';
EDIT
To get the elements by classname, then retrieve the id :
var names=document.querySelectorAll(".name"),l;
while(l--){
console.log(names[l].id);
}
or if i didn't understand correctly
html
<div class="spaghetti" id="pizza"></div>
js
document.querySelector(".spaghetti#pizza")
EDIT2
html
<div id="container1"><div class="my-class"></div></div>
js
document.querySelector("#container1>.my-class")

Easier solution, any use case. Query your selector:
let find = document.querySelector('.selector');
create some html as a string
let html = `put your html here`;
create element from string
let div = document.createElement('div');
div.innerHTML = html;
Append new html you created to selector
find.appendChild(div);

Related

How do we convert jQuery prepend() to VanillaJS [duplicate]

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'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.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

Dynamically add new element and change its content

I want to "copy" a certain elements and the change some of the text inside them with a regex.
So far so good: (/w working fiddle - http://jsfiddle.net/8ohzayyt/25/)
$(document).ready(function () {
var divs = $('div');
var patt = /^\d\./;
var match = null;
for (i = 0; i < divs.length; i++) {
match = ($(divs[i]).text().match(patt));
$(divs[i]).text($(divs[i]).text().replace(match[0], "5."));
}
});
HTML
<div>1. peppers</div>
<div>2. eggs</div>
<div>3. pizza</div>
This works exactly the way I want it, but I want to add some of the content dynamically, but when I try to change the content of the copied divs, nothing happens.
Please refer to this fiddle:
http://jsfiddle.net/8ohzayyt/24/
I have put some comments, to be more clear what I want to achieve.
I thing that your problem is that you're not passing an element to your changeLabel function, but just a string.
Look at this solution: http://jsfiddle.net/8ohzayyt/26/
Here is the line I changed to make your code work:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
I just wrapped your HTML in $(). this creates an element from the string.
try:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
EDIT:
Brief explanation What I've done.
In order to make $(el).find('div'); work changeLabel() needs an element. Instead of passing newContent as a string doing the above will make it pass as an element which will make $(el).find('div'); work.

Adding div element to body or document in JavaScript

I am creating a light box in pure JavaScript. For that I am making an overlay. I want to add this overlay to body but I also want to keep the content on the page. My current code adds the overlay div but it also removes the current contents in body. How to add div element and keep contents on body?
var el = document.getElementById('element');
var body = document.getElementsByTagName('body');
el.innerHTML = '<p><a id="clickme" href="#">Click me</a></p>';
document.getElementById('clickme').onclick = function (e) {
e.preventDefault();
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
}
Using Javascript
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);
Using jQuery
$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');
Try this out:-
http://jsfiddle.net/adiioo7/vmfbA/
Use
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
instead of
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
Edit:-
Ideally you should use body.appendChild method instead of changing the innerHTML
var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Instead of replacing everything with innerHTML try:
document.body.appendChild(myExtraNode);
improving the post of #Peter T, by gathering all solutions together at one place.
Element.insertAdjacentHTML()
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[#id="answer-33669996"]';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
The most underrated method is insertAdjacentElement.
You can literally add your HTML using one single line.
document.body.insertAdjacentElement('beforeend', html)
Read about it here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
The modern way is to use ParentNode.append(), like so:
let element = document.createElement('div');
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.append(element);
You can make your div HTML code and set it directly into body(Or any element) with following code:
var divStr = '<div class="text-warning">Some html</div>';
document.getElementsByTagName('body')[0].innerHTML += divStr;
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
The best and better way is to create an element and append it to the body tag.
Second way is to first get the innerHTML property of body and add code with it. For example:
var b = document.getElementsByTagName('body');
b.innerHTML = b.innerHTML + "Your code";
Here's a really quick trick:
Let's say you wanna add p tag inside div tag.
<div>
<p><script>document.write(<variablename>)</script></p>
</div>
And that's it.

I generated html code (lots of divs) with javascript. Now I want to find the generated divs with GetElementById

GetElementById works if I manually added a div id="something" inside the body and use window.onload = init method in the script to get it. Works great.
But if I used a for loop to generate divs where id's is 1,2,3 and so on. I can't get it. Is there a way to get to those generated divs?
This is what generates the html code (just to be clear what I mean):
for(i=0; i<randomizeColoursList.length; i++)
{
document.getElementById("renderColors").innerHTML +=
'<div class=\"box\"><div class=\"' + i + '\"><font color=\"'
+ randomizeColoursList[i] + '\">'
+ "" + '<img src=\"dist/card_bg.gif\"></div></div>';
}
Generates one of these:
<div class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>
Div with class 8 is the id I want to get for example. But is says it's null.
Thanks.
The id is null because you haven't specified it in your markup creation. Looks like you're assigning the id value to class instead.
Generate something more like this:
<div id="div1" class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>
Also, you don't need to use font tags, nor should you use them. Just add the styling to the div.
<div id="div1" class="8" style="color:#3be6c4;"><img src="dist/card_bg.gif"></div>
The way you're going about this is a little backwards. If you write your code like I have below, then you don't need to give the divs IDs, you end up with an array full of references to them anyway.
var i, div, img;
var createdDivs = [];
for(i=0; i<randomizeColoursList.length; i++)
{
div = document.createElement('div');
img = document.createElement('img');
div.className = "box";
div.style.backgroundColor = randomizeColoursList[i];
div.style.color = randomizeColoursList[i];
img.src = "dist/card_bg.gif"
div.appendChild(img);
document.getElementById("renderColours").appendChild(div);
createdDivs.push(div);
}
Live link: http://jsfiddle.net/7HjLL/

How can I implement prepend and append with regular JavaScript?

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'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.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

Categories

Resources