I am using the following code to print a paragraph when the button is clicked:
document.querySelector('button')
.addEventListener('click', function() {
const p = document.createElement('p');
p.id = "text";
const val = document.getElementById('forminput').value;
if (val.length) {
p.innerHTML = val;
document.querySelector('div').appendChild(p);
}
});
When the paragraph is posted, I want it to retain the same CSS styling as well as the same onclick function as the styling and function I use for other content.
What would be the right way to do it?
If you have some styling set up for your p tags already, then this would automatically apply when you render the new p tag.
Else you can create a custom css class that holds the styling you're wanting to apply, and then add this classList to your newly rendered p tag as follows:
const p = document.createElement('p');
p.classList.add('your-class');
Related
FYI: It is desirable that solutions be strictly vanilla Javascript.
How can I append an HTMLElement object to the middle of an element?
Here's a sample with a bit of what I mean.
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><br>There is some text.'
document.body.appendChild(paragraph)
const wrappper = document.createElement('div')
const button = document.createElement('button')
button.onmouseup = () =>
{
// Do something
}
wrapper.appendChild(button)
Now imagine for a moment that I want to put the wrapper element inside of the paragraph element. But, not at the beginning or the end of it, but rather somewhere in the middle such as between the <br> tags. (But not necessarily after a tag) This can be done rather easily by taking the outerHTML of wrapper and inserting it into the paragraph's innerHTML via substrings, but this presents a problem. The resulting elements now in the flow of the html page are not the same as wrapper or button, which is evident when logging them, or when there is no onmouseup event being triggered.
So, ultimately, how do I put the exact HTMLElements referenced by the defined variables into the flow of the document in the middle of the contents of another element?
Find the <br> element and use insertAdjacentElement to insert after it.
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><br>There is some text.'
document.body.appendChild(paragraph)
const wrappper = document.createElement('div')
const button = document.createElement('button')
button.innerText = 'Click';
const br = paragraph.querySelector("br");
br.insertAdjacentElement('afterend', button);
Maybe have a temporary <span> with a known id and then replace it with the element you wish to replaceWith would do...
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><span id="destination"></span><br>There is some text.'
document.body.appendChild(paragraph)
const wrapper = document.createElement('div')
const button = document.createElement('button')
button.innerText = "here"
button.onmouseup = () =>
{
// Do something
}
wrapper.appendChild(button)
let destination = document.querySelector("#destination")
destination.replaceWith(wrapper)
I create a class and elements inside the class using the following function in javascript and add it to another class using appendchild function.
function createClass(menu)
{
console.log('class entered');
var newNode = document.createElement('div');
newNode.className = 'item';
var input = document.createElement('input');
input.setAttribute("type","checkbox");
input.setAttribute("id",menu);
input.innerText=menu;
var label = document.createElement('label');
label.setAttribute("for", menu);
label.innerText=menu;
input.appendChild(label);
newNode.appendChild(input);
return newNode;
}
But, the contents is not displayed in the html page. The class is added. When the body of the html is displayed in the console, the class is added to the body but before the inner text, it says "shadow content (user Agent)".
How do I make them visible?
You've create new DOM elements but never actually attached them to the current document. The missing part is to to add your new DOM element to the document:
document.body.appendChild(createClass('hello'))
I have a list with people's data inside it has a li element with 3 p tags inside, one for name, one for address and one for email.
I filled this list manually but due to some changes to my code I had to rewrite this so the html would be made with javascript.
My code looked like this
<p class="adres">#logopedist.Adres</p>
<p class="email">#logopedist.Email</p>
<p class="mobiel">#logopedist.Mobiel</p>
I rewrote this to build the html using javascript. This looks something like this.
var li = document.createElement('li');
li.className = "lijst";
li.id = "lijst";
li.onclick = "ficheVullen(this)";
p.className = "naam";
p.innerHTML = objLogos.Naam[i];
li.appendChild(p);
p.className = "adres";
p.innerHTML = objLogos.Adres[i];
li.appendChild(p);
var p = document.createElement('p');
p.className = "mobiel";
p.innerHTML = objLogos.Mobiel[i];
li.appendChild(p);
My list generates properly. But in my old code I had this at the start of the list.
<li class="lijst" onclick="ficheVullen(this)">
Whenever you would click an li element it would fill a div with the info from the p tags inside that li, so it would fill the div with name, address, mobile,etc
I cannot seem to get this function to work anymore. It only works on the very first LI element and only works for the name. Even though my code is the same and I append classes to the tags like it had in my old code.
The function looks like this:
function ficheVullen() {
FicheNaam = document.getElementById("FicheNaam");
FicheAdres = document.getElementById("FicheAdres");
FicheGSM = document.getElementById("FicheGSM");
FicheNaam.innerHTML = this.querySelector('.naam').textContent;
FicheGSM.innerHTML = this.querySelector('.mobiel').textContent;
FicheAdres.innerHTML = this.querySelector('.adres').textContent;
I get this error now. Cannot read property 'textContent' of null
I call this function here:
window.onload = function() {
changePage(1);
document.getElementById("lijst").addEventListener("click", ficheVullen);
};
The changepage function is part of my pagination where I use javascript to build the list.
When I move the eventlistener out of this I get this error: Cannot read property 'addEventListener' of null.
I hope this gives enough context
You have to use setAttribute to set id.
elm.setAttribute("id", "uniqueId");
Your case : li.setAttribute("id", "lijst")
li.id = "lijst"; will add "id" to object not as attribute
const parent = document.getElementById("container")
let elm = document.createElement("p")
elm.setAttribute("id", "pElm")
elm.innerText = "p tag"
parent.append(elm)
document.getElementById("pElm").style.background = "red"
<div id="container"></div>
I'm working on a Chrome extension which displays a dynamically loaded popup. User can change settings to choose its color. My issue is that I would like to change some :hover attributes of popup's elements, but I don't find how.
My current code:
var myDiv = document.createElement('a');
myDiv.style.background = myIcon;
myDiv.style.backgroundImage = myURL;
What I would like to add (not working code atm):
myDiv.hover.style.backgroundColor = myColor;
Thank for help.
You can't set styles for pseudoclasses with JavaScript. Instead, you must define them with CSS. You can use JavaScript to dynamically add CSS to a page, though:
var style = document.createElement("style");
style.appendChild(
document.createTextNode("some-selector:hover { /*...*/ }")
);
document.querySelector("head").appendChild(style);
...or similar.
Here's an example adding an element with class foo to a document, along with dynamically-defined styles for it:
var foo = document.createElement("div");
foo.className = "foo";
foo.innerHTML = "This is foo, hover me";
document.body.appendChild(foo);
var style = document.createElement("style");
// Pick a color at random
var color = ["red", "blue", "green"][Math.floor(Math.random() * 3)];
style.appendChild(
document.createTextNode(
".foo:hover { background-color: " + color + " }")
);
document.querySelector("head").appendChild(style);
I have a javascript function designed to dynamically append text to my document (and slides it down with JQuery). I create a new "p" element, and then I want to add text to it, but I need this text to have several formats. For example, I need the first part to be italicized, second part to be underlined, and third part to be white. As of now, I managed to get three different "div" elements with their own text nodes, each with their own style, but this makes it on three separate lines. I need it all on one line. Is there any way I can insert HTML tags into a text node, or somehow split the internal string up so I can style each part separately?
This code demonstrates the closest I got, but this puts each styled text node on different lines, and I need it all on one line in that p element:
function append_announcement(time_string, user_by, text){
newp = document.createElement("p");
head = document.createElement("span");
headt = document.createTextNode("You wrote: ");
head.appendChild(headt);
body = document.createElement("div");
bodyt = document.createTextNode(text);
body.appendChild(bodyt);
body.setAttribute("style", "color: white");
foot = document.createElement("div");
foott = document.createTextNode("Done.");
foot.appendChild(foott);
newp.appendChild(head);
newp.appendChild(body);
newp.appendChild(foot);
newp.setAttribute("align", "center");
newp.style.display = "none";
document.getElementById("announcement_posts").insertBefore(newp,
document.getElementById("announcement_posts").firstChild);
$("p").slideDown("slow");
}
Change the <div>s for <span>s, they're displayed inline by default.
Alternatively you could apply a class to the <div> elements you create and set that class to display: inline-block; using CSS.
Example
function append_announcement(time_string, user_by, text){
newp = document.createElement("p");
var i = document.createElement("i");
i.textContent = ("You wrote ");
var span = document.createElement("span");
span.textContent = text;
span.style.color = "white";
var u = document.createElement("u");
u.textContent = " Done.";
newp.appendChild(i);
newp.appendChild(span);
newp.appendChild(u);
newp.setAttribute("align", "center");
newp.style.display = "none";
document.getElementById("announcement_posts").insertBefore(newp,
document.getElementById("announcement_posts").firstChild);
$("p").slideDown("slow");
}
You want to create elements that display inline like <i>, <u> or <span>