I want when I click, a new DIV will be created with an image inside it.
This is the code I tried:
let addTask = document.querySelector('#addTask');
addTask.addEventListener('click', ()=>{
//create DIV, This part of the code works well
let createNewDiv = document.createElement('div');
createNewDiv.innerHTML = writeTask.value;
document.body.appendChild(createNewDiv);
createNewDiv.className = 'tasks';
//create an image inside the DIV element, This part of the code does not work
let imageDelete = document.createElement('img');
imageDelete.src = 'deleteImage.jpg';
document.body.tasks.appendChild(imageDelete);
});
Where's my error?
Any comment or feedback can help me. Thanks
createNewDiv.appendChild(imageDelete)
It appears you are creating an element with a class .tasks.
Afterwards you try to access it using document.body.tasks.
Elements with a class cannot be accessed directly using this method.
Elements with a id however, can.
So you need to change the .tasks element to include the id tasks or rewrite the accessor to document.querySelector('.tasks')
document.querySelector('.tasks').appendChild(imageDelete);
Related
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/
I have a function called "StartMsg"
that I want to add text to a div element with the id "Screen". But sadly I known only basic JS, here is what I have so far;
function StartMsg() {
document.getElementById('Screen').innerHTML = "The game was created.";
}
But it overwrites all of my previous text (Yes I know it's supposed to do that, I'm trying to find a way to not overwrite but add!).
Use textContent and con-cat the new string
document.getElementById('Screen').textContent += " The game was created.";
JSFIDDLE
You can try createTextNode() method,
var your_div = document.getElementById('Screen');
var your_text = document.createTextNode("text added");
your_div.appendChild(your_content);
Using innerHTML will remove all listeners within the div element
You can also use the append method.
For example:
$('variable').append('some text');
The problem is when I try to create custom element this way
var el= document.createElement('my-el');
el.setAttribute('tag-model', "[[myBinding]]");
it creates element without its attributes. How to construct custom element with all its attributes and then append to HTML to initilize them?
Thank you!
See this
It basically says to do it like that:
var dynamicEl = document.createElement("my-element");
dynamicEl.setAttribute("id", "my-element-id");
dynamicEl.setAttribute("greeting", "Hello, Good Morning.");
document.body.appendChild(dynamicEl);
However, if you want to change properties directly, it wont work with setAttribute. You have to do it like that:
var dynamicEl = document.createElement("my-element");
dynamicEl.greeting = 'Waaazaaaa???';
document.body.appendChild(dynamicEl);
I'm trying to create a JavaScript where you write a message and the time and message appears on the website. The function doing this is "renderMessage". However, it includes an image you can click to delete that message and then I want to write all the remaining ones again. Problem is that I don't know how to save some sort of ID so I know which image was clicked so I delete the correct position in the array of messages.
The code for renderMessage is:
function renderMessage(theMessage, theMessages){
var text = document.createTextNode(theMessage.getText());
var time = document.createTextNode(theMessage.getDate());
var div = document.getElementById("writeMessages");
div.appendChild(text);
div.appendChild(time);
var image = document.createElement('img');
image.src = 'img/deletePic.png';
div.appendChild(image);
div.appendChild(document.createElement('br'));
image.onclick = function(e){
theMessages.splice(); // This is where I don't know how to remove the correct one
removeAll(theMessages); // This removes all html code in the div and writes
// the array again (hopefully this time with the correct
// element removed from it)
};
}
Firstly, thumbs up for using plain js.
I would say you enclose the message, time and the image into another element. My be a ul li block. And, when you render the messages in DOM, you set the message id as id attribute of the li so it will be something like this
<ul>
<li>Message 1 - 10:21 PM <img src="remove jpg"/></li>
<li>Message 2 - 10:22 PM <img src="remove jpg"/></li>
</ul>
and your js code can be,
image.onclick = function () {
var message_id = this.parentNode.id;
// here you got the message id.
// splice your message array and render
}
Why are you re-rendering all the messages? You could simply
// splice your message array and render
var li = this.parentNode;
li.parentNode.removeChild(li);
}
you can save the id of the message inside an attribute of the element. eg <div class="your_message_container data-id="14">...</div>
Using jquery for example you can read that attribute with $(your_selector).attr("data-id"); and write it with $(your_selector).attr("data-id", "new_value");
As an alternative, also have a look at http://api.jquery.com/jquery.data/
Edit:
i made you a fiddle with pure js: http://jsfiddle.net/A64zh/2/ Note that the id of the message element must equal the data-message-id attribute of your delete image.
the advantage of using an element attribute for storing the id is that your javascript does not depend on the html structure like it does if you are using something like this.parentNode.parentNode.removeChild.... which would need to be changed if you would add more html layers in between the two
I have a function that appends a div to another div.
Something like:
var div = ...some html
$("#mydiv").append(div);
However I want to do some stuff to the div I just added. Currently I want to hide a sub part of the new div, and add a object as data. Something like
var div = ...some html
$("#mydiv").append(div);
$(my new div).find(".subDiv").hide();
$(my new div).data('user',object);
But how should I get the the new div I created? Is there a way to create it and then preform these actions, and then append it? Or should I append it and then retrieve it and modify it?
Efficiency is important as this will be iterated for search results...
Thanks!
I used this as my solution thanks to Tricker:
var div = ...a lagre piece of html;
var newDiv = $(div);
newDiv.find("[show='contractor']").hide();
newDiv.data('user', userObject);
$(appendDiv).append(newDiv);
Thanks!
The way u want is like this:
var new_obj = $('<div class="subDiv"></div>');
$("#my_div").append(new_obj);
//You dont have to find the subdiv because the object "new_obj" is your subDiv
new_obj.hide();
new_obj.data('user',object);
Does .append() not return the new item?
var myNewDiv= $("#mydiv").append(div);
since it will always be the last child div, I believe you can access it via $("#myDiv div:last-child")