Append to div, rather than body [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Inserting an element
How to do insert After() in JavaScript without using a library?
I have this little bit of javascript in a project which adds a chat window after the body of the page, I'd like to change it so that it adds the chat window AFTER my specified div "myPublisherDiv". I think this is pretty simple, any ideas? Thanks in advance!
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
document.body.appendChild(div);

This is a bit trickier. insertBefore is simple, for inserting after a node I wrote a litte helper function:
function insertAfter(newElement, referenceElement) {
referenceElement.parentNode.insertBefore(newElement, referenceElement.nextSibling);
}
var div = document.createElement('div');
...
insertAfter(document.getElementById("myPublisherDiv"), div);
But see also https://stackoverflow.com/a/1559632/1048572

This should do it..
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
var target = document.getElementById('myPublisherDiv');
target.parentNode.insertBefore(div, target.nextSibling);
ripped from How to do insert After() in JavaScript without using a library?

Put an id to your div
<div id="myDiv">..</div>
And then append things to it with the appendChild:
document.getElementById("myDiv").appendChild(div);

Related

Create html elements inside tooltip for a chrome extension

I want to create an HTML element (a div) using javascript to use that as a tooltip.
I can create the simple element by doing:
const element = document.createElement("div");
element.id = "myID"
and that works fine...however, I want to add a table (and some other HTML) inside the tooltip, so I was trying to do
element.appendChild(childElement); //where the childElement is another document.createElement("") that contains all the HTML I want.
or:
element.insertAdjacentHTML('afterbegin', '<table></table>');
however, nothing happens. there's no error, but it won't append it either. Am I missing something?
If it matters, this is happening inside the contentScripts.js of a chrome extension I'm building.
EDIT
Full code of div creation:
const element = document.createElement("div");
element.id = "tooltip-creation";
element.classList.add("tooltip");
const childElement = document.createElement("div");
childElement.id = "data";
//I've attempted to do .appendChild, innerHTML, and .insertAdjacentHTML (as can be seen here) and neither works but no error is given.
element.appendChild(childElement);
element.insertAdjacentHTML('afterbegin','<table border="1"><tr><td><strong>OMG</strong></td></tr></table>');
element.innerHTML = "<table border="1"><tr><td><strong>OMG</strong></td></tr></table>";
Separately I have 2 functions that do:
document.addEventListener("mouseover", function(e){
if (e.target.classList.contains("tooltip")) {
createTooltip(e);
}
});
document.addEventListener("mouseout", function(e){
if (e.target.classList.contains("tooltip")) {
removeAllTooltips();
}
});
I think your issue is that you're not actually appending the tooltip to anything. You need to append your element to a node that is already in the DOM. Here is a working example (without any CSS) that I got from your code, the only difference being that I appended the element node to an existing element in the DOM called root.
https://jsfiddle.net/irantwomiles/09o7vuj5/12/

How To Grab Image Source From CSS Background Image [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
This is my first question ever, please show some love!
I'm trying to grab the background image from a div element and append it to a div every time I push a bottom. Below is the mockup code:
<div class="img"></div>
.img {
background: url("local image file");
}
function addImage(imageSrc) {
var imageSrc = document.getElementByClassName('img')[0].getComputedStyle.background
}
I could not find a way to grab the local path inside the background url(""). Can someone please help? I only know vanilla Javascript.
Thank you!
Using the getComputedStyle on the window.
const img = document.getElementsByClassName('img')[0];
const url = getComputedStyle(img).backgroundImage.slice(5, -2);
I get the URL from getComputedStyle(element).backgroundImage then slice out the url and brackets surrounding the link
Use:
window.getComputedStyle(document.getElementsByClassName('img')[0]).getPropertyValue('background')
getComputedStyle is a property of window. Since window is always implicit, it can be omitted. Here's your solution:
const imgSrc = getComputedStyle(document.querySelector('.img')).backgroundImage.slice(5, -2);
console.log(imgSrc);
.img{
background:url('test.png');
}
<div class='img'></div>

Variable attributes disapearing when put inside div

Probably a simple question but I can't seem to find the answer. I am dynamically creating a page where I can share twitter links.
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
etc..
I then append it to the div I want such as
$('#doc').append('<img(miscellaneous HTML)>'+twitter)
What I have above works but for CSS formatting purposes I want the image with the twitter share button to be a sub-block. So I create something like this
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
But when I do this it seems all the attributes of the twitter var are lost, only printing http: // twitter.com/share on the page instead of the button.
I feel it's probably a basic concept I am forgetting.
You are tring to concatenate a DOM object and a String via this code
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
This twitter variable contains a DOM object and the rest of the append block is String.
Try this:
var div = $('<div id="innerblock'+i+'"><img(miscellaneous HTML)></div>').append(twitter);
$('#doc').append(div);
What I would do is instead of appending the HTML instead you can create the innerblock div and the img tags using document.createElement and append the twitter to the img and the img to the div before appending it all to #doc
You can not concatenate a sting and a DOM node.
var div = $("<div id="innerblock'+i+'">").append("<img />").append(twitter);
or
var div = $("<div/>", {id : "innerblock" + i).append("<img />").append(twitter);
Try substituting .outerHTML String of twitter for DOM element Object twitter ; also adding closing sing quote ' at end of string parameter provided to .append()
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
var i = 0;
$('#doc').append('<div id="innerblock'+i+'"><img />'+twitter.outerHTML+'link</div>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="doc"></div>

Adding a Values into a div created from document.createElement

I have a DIV that is created from document.createElement,, I have a few text and a image that needs to be added to this DIV. Could some one suggest me the best way to do it? The image path is given in the image variable. Below is the code that i have already written. contentattachpoint is another DIV that is there in the HTML page which is got by
var contentattachpoint=document.querySelector('.contentattachPoint');
var year="Year of Manufacture:"+arr[i].year;
var power="Engine Power:"+arr[i].power;
var description="Description:"+arr[i].description;
var image=arr[i].image;
var details = document.createElement("div");
details.setAttribute("id", "details");
details.className = "details";
details.value=year+power+description;
contentattachpoint.appendChild(details)
Thanks in advance.
By what I understand of you question I consider that you need text and image both in the div that you created so do something like this
details.innerHTML = description + "<img src='"+image+"'>";
just do what you are already doing use details.appendChild()
Look at this sample example:
just created a demo example to show you how to dynamically create a div and add paragraph tag and image tag to it.
http://jsfiddle.net/2LAYS/2/
If you are using jQuery, use the .append() function.
Example:
$('#details').append('<img src="' + image + '" />');
you should also take a look at Prepend
Source(s)
jQuery API - append()
jQuery API - prepend()

Getting the first element from <body> then insertBefore()

I've been at this for a few hours now and am about to start ripping hair out. Basically what I need to do is get the first element that appears in the body and then insert another element before it.
I've tried the following to get the first element with no success (undefined or null)
window.document.body.firstChild
document.getElementsByTagName("body").firstChild
document.getElementsByTagName("body")[0].firstChild
window.document.documentElement.childNodes[1].childNodes[0]
And a whole slew of mixed and matched attempts of the previous snippets. I've also tried just getting the body then appendChild() with no success either.
Any help here is appreciated. Thanks in advance.
Yes, document.body.firstChild is correct. It's likely that you are overlooking the fact that insertBefore is a method of the parent element, and it takes the new element before the existing one. For example:
var addedElement = document.createElement('p');
addedElement.appendChild(document.createTextNode('Hello, world!'));
var body = document.body;
body.insertBefore(addedElement, body.firstChild);
You want something like this:
var first = document.body.children[0];
var beforeEle = document.createElement("div");
beforeEle.innerHTML = "I'm the first element in the body!";
document.body.insertBefore(beforeEle, first);
The most elegant solution to prepend an element to the body I could up with is a one-liner:
document.body.insertBefore(element, dom.document.body.firstChild)

Categories

Resources