Add css before appending child - javascript

So I have a div (with the id of "thecolor2") that I want to append to an unordered list, but before I append it, I want to set its background color to a variable which has the value of a hex code. However, for some reason, it doesn't take in the color.
Here is the CSS:
#thecolor2{
height: 50px;
width: 50px;
border-radius: 100px;
border: 1px solid yellow;
position: relative;
bottom: 635px;
}
Her is the HTML:
<ul id = "allposts"></ul>
And here is the JS:
var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
$("#thecolor2").css("background-color", color);
thestream.appendChild(oneofpost);
thestream.appendChild(thecolor2);

You cant use a jQuery ID selector to match a node which hasn't been added to the document tree. You can simply use plain DOM to set its inline CSS style like this:
thecolor2.style.backgroundColor = color

As described by Carlo in another answer, you cannot use the jQuery selector to select elements that haven't been added. You can however, turn a created DOM element into a jQuery object by doing:
var thecolor2 = $(document.createElement('div'));
However, if you're going to be using jQuery then I suggest writing everything in jQuery, otherwise stick with using pure JavaScript for everything.
jQuery
var thestream = $('#allposts');
var oneofpost = $('<li></li>');
var thecolor2 = $('<div></div>');
thecolor2.prop('id', "thecolor2")
.css({
backgroundColor: color
}).appendTo(oneofpost);
thestream.append(oneofpost);
See jsFiddle
JavaScript
var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
thecolor2.style.backgroundColor = color;
oneofpost.appendChild(thecolor2);
thestream.appendChild(oneofpost);
See jsFiddle
Also I'm assuming you're trying to append a list item to the ul, so I corrected the code you had there with appendChild.

Related

How to programmatically append a newly created div to an existing one?

I have some trouble with appending a new div to an existing parent that I just created. After creation of the parent I check it's existence. But when I want to append the child to it after selecting the parent via it's id I get an error. What do I do wrong?
var uiDiv = document.createElement("div");
uiDiv.id = "f_jsonuiDiv";
uiDiv.innerHTML = "jsonUI controls";
console.log("uiDiv");
console.dir(uiDiv); //shows uiDiv object
//select container div
const parentId = "f_jsonuiDiv"; //which is the id of the newly created container div
console.log("parentId: ",parentId);
var parElement = document.getElementById(parentId);
console.log("parElement: ");
console.dir(parElement); //says: null !
//create directly
//const newDiv = parElement.createElement("div"); //throws error as parElement does not exist ......
//create first, then append
const newDiv = document.createElement("div");
newDiv.innerHTML = "NEW DIV";
//parElement.appendChild(newDiv); //throws error as parElement does not exist ......
uiDiv.appendChild(newDiv); //does not throw an error ```
Seems like you need to add uiDiv to body (or any other parent) first, in order to get it with getElementById
document.body.appendChild(uiDiv);
// This should be valid now
const parElement = document.getElementById(parentId);
You need to put the script after the body let the DOM be created .
Or warp your code with
window.addEventListener('DOMContentLoaded', (event) => { //put your code here });
it will run after the page is loaded
A would advise to use insertAdjacentElement and insertAdjacentHTML. It makes your life easier.
// insertAdjacentElement returns the newly created element
const uiDiv = document.body.insertAdjacentElement(`beforeend`,
Object.assign(document.createElement("div"), {
id: "f_jsonuiDiv",
innerHTML: "jsonUI controls" })
);
// so now you can inject it wit some html
uiDiv.insertAdjacentHTML(`beforeend`,`<div>HI, I am the NEW DIV in town</div>`);
#f_jsonuiDiv div {
color: red;
padding: 2px 1em;
border: 1px solid #AAA;
max-width: 400px;
text-align: center;
}

JavaScript replace works in console, but not on the website

I've been trying to create a list of tags and separate them using commas. I'm using Webflow and sadly it's not possible in their cms.
I thought of a workaround where I would replace the commas with code using JavaScript.
Here's the code:
function tags() {
var tag = document.getElementById("tag__wrap").innerHTML;
str = tag.replace(/,/g, '</p><p class="tag__wrap">');
}
tags();
console.log(str);
For some reason the code works fine when I look it up in the console, but doesn't actually show anything on the actual website.
Any thoughts?
If your goal is to create multiple elements in place of the single element (that has the comma separated tags), then you need to manipulate the DOM. It is not enough to assign HTML to a string variable.
There are many ways to do this. Here is one:
function tags() {
var elem = document.getElementById("tag__wrap");
var tags = elem.textContent.match(/[^,\s]+/g) || [];
elem.textContent = tags.shift();
for (let text of tags) {
var newElem = elem.cloneNode();
newElem.textContent = text;
elem.insertAdjacentElement("afterend", newElem);
elem = newElem;
}
}
// Delay the change, so you can see before & after in the snippet
setTimeout(tags, 1000);
#tag__wrap {
background: lightblue;
display: inline-block;
margin: 5px;
padding: 3px 8px;
border-radius: 4px;
}
<p id="tag__wrap">algorithm,javascript,html,css</p>

Add a link to only pseudo element with javascript

I'm trying to add a link to a pseudo element, but not the parent element. I'm brand new to javascript, and after doing a lot of research I've been able to add a link to both the parent and pseudo elements, but I don't want the parent to be linked. It unfortunately will have to be a pseudo element because I don't have the option of adding another div to the html.
I have a fiddle which is kind of a mash of a few different fiddles I've found. Please let me know if I'm on the right track, or if this is even possible. And let me know if there is any additional information I can provide.
One more thing to note, is that the parent div will have child divs as a menu, which is why I'd prefer the parent not be clickable. But after testing (at least in the fiddle as it is now) the child links are still be clickable and correct, and these will still need to be clickable as well.
Thanks!
http://jsfiddle.net/mqb9juhn/1/
<div id="example">
<div class="example-child">
Test Test 2
</div>
</div>
#example {
position: relative;
}
#example::before {
content: "click here"!important;
font-size: 16px;
display: block;
padding: 20px;
background-color: #ffff00;
top: 0;
}
var UID = {
_current: 0,
getNew: function(){
this._current++;
return this._current;
}
};
HTMLElement.prototype.pseudoStyle = function(element,prop,value){
var _this = this;
var _sheetId = "pseudoStyles";
var _head = document.head || document.getElementsByTagName('head')[0];
var _sheet = document.getElementById(_sheetId) || document.createElement('style');
_sheet.id = _sheetId;
var className = "pseudoStyle" + UID.getNew();
_this.className += " "+className;
_sheet.innerHTML += "\n."+className+":"+element+"{"+prop+":"+value+"}";
_head.appendChild(_sheet);
return this;
};
$(document).ready(function(){ $("#example").on('click', function(){
window.location = "http://www.google.com/";});
});
var div = document.getElementById("example");
div.pseudoStyle("before","color","#ff0000");

Modify previously defined style in JS

A function for creating style constructed as follows
function createStyle(css) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
var textNode = document.createTextNode(css);
style.append(textNode);
}
head.append(style);
}
inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab
createStyle(`
.tab button {
background: inherit;
float: left;
outline: none;
border: none;
padding: 8px 6px;
width: 60px;
cursor: pointer;
}
`);
and a HTML element using the style
var div = document.createElement("div");
div.className = "tab";
parent.append(div);
is also created. So it all works.
After that I need to modify the style with class name tab, where following code
var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];
is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.
The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].
Proposed solution
Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function
// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
var N = document.styleSheets.length;
var styles = document.styleSheets;
for(var i = 0; i < N; i++)
{
if(styles[i].rules[0].selectorText == style)
styles[i].rules[0].style[attr] = value;
}
}
which is called
changeStyleAttribute(".tab", "width", "299px");
and works. I hope there is another better and simpler solution.
You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);
Refer to this link: How to change/remove CSS classes definitions at runtime?.
Hope this helps.

Javascript add margins between each object in an array

I'm new to Javascript and I'm building a connect four game to learn about javascript. The problem is that I am unable to add margins between the 'o' so they all look clumped together.
I would like help adding margins or padding between the 'o's. Some thoughts are that I may need to add each row of 'o' in a table. However, I'm updating it through the javascript function. How do I get around that?
My javascript file
var first_row = ['o','o','o','o','o','o','o'];
onload = function ()
{
document.getElementById("row1").innerHTML = first_row;
}
HTML file
<h1 class="space" id="row1"></h1>
In pure javascript (not using jquery) with a for in loop than append spans with the '0's for styling.
var first_row = ['o','o','o','o','o','o','o'];
var row = document.getElementById('row1');
for (var i in first_row) {
var span = document.createElement('span');
span.innerHTML = first_row[i];
row.appendChild(span);
}
See here: http://jsfiddle.net/95JqK/17/
You'll have to encapsulate them into tags and put css rules on them.
A simple solution would be:
var first_row = ['<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>'];
onload = function ()
{
document.getElementById("row1").innerHTML = first_row;
}
And in a css file:
span {
margin: 0 10px 0 10px;
}
Perhaps you could use CSS on the class="space" elements
.space{
padding: 8px;
}

Categories