I created a simple library, and I'm trying to change the style of an element in the library. Very simple thing.
content[0].removeChild(content[0].firstElementChild);
content[0].style.backgroundColor = 'green';
I tried it in Chrome, and it works like a charm. I then tested it in Microsoft Edge and Internet Explorer, and they both don't recognize the element I'm trying to change.
They give the following error:
Unable to get property 'removeChild' of undefined or null reference
How can I fix this so that it works in all browsers?
codePen
function veryUsefullLibrary(parentElem) {
var outerWrapper = document.createElement('div'),
innerWrapper = document.createElement('div'),
content = parentElem.children;
function changeFunction(e) {
console.log(content);
content[0].removeChild(content[0].firstElementChild);
content[0].style.backgroundColor = 'green';
}
while (content.length)
innerWrapper.appendChild(content[0]);
content = innerWrapper.children;
var radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'simSlider';
radio.addEventListener('change', changeFunction);
parentElem.appendChild(radio);
outerWrapper.appendChild(innerWrapper);
parentElem.appendChild(outerWrapper);
}
var overall = document.getElementById('overall'),
lib = new veryUsefullLibrary(overall);
#first {
width: 500px;
height: 386px;
}
<div id="overall">
<div class="content" id="first">
<img src="https://verkoren.files.wordpress.com/2013/05/junk-dump-22918.jpg" />
</div>
</div>
This seems to make it work.
function changeFunction(e) {
content = innerWrapper.children;
console.log(content);
content[0].removeChild(content[0].firstElementChild);
content[0].style.backgroundColor = 'green';
}
Related
I have the following fa-icon:
<div id="notification">
<div id="info">
<div class="service">
<i class="fas fa-music"></i>
<h1 class="name"></h1>
</div>
</div>
</div>
I tried the following to color it with javascript:
var Music = (swatches.DarkVibrant.getHex());
document.getElementById("info").getElementsByClassName("service")[0].style.color = Music;
// Gave i element this id
document.querySelector('#music').style.color = Music;
document.querySelector('.fas fa-music').style.color = Music;
However none of them work, how could I achieve this?
Edit: it seems like it only works outside my function, why does it not work when its inside?
// Works
document.querySelector('.fas').style.color = "blue"
function mainUpdate(type) {
if (type == "music") {
if (isplaying) {
document.querySelector('.name').innerHTML = "Now playing";
document.querySelector('.details').innerHTML = "• " + album;
document.querySelector('.song').innerHTML = title;
document.querySelector('.artist').innerHTML = artist;
var milli = new Date().getMilliseconds();
var albumart = document.querySelector("#artworkImage");
albumart.src = "/var/mobile/Documents/Artwork.jpg?" + milli;
albumart.addEventListener('load', function () {
var vibrant = new Vibrant(albumart);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
var Name = (swatches.DarkVibrant.getHex());
var Music = (swatches.DarkVibrant.getHex());
}
document.querySelector('.name').style.color = Name; // Works
document.querySelector('.fas').style.color = "blue" // Doesnt work
});
}
}
}
Since 5.0 uses SVG try
document.querySelector('.fas fa-music').style.fill = Music;
If this does not work then you will have to select SVG inside and apply rule in it
Do something like
document.querySelector('.fa.fa-sign-in').style.color = "green"
You have a mistake in your selector. For your case, the correct line to modify the styles will be
document.querySelector('.fas.fa-music').style.color = "green"
Change "green" to your color
Did you try the following code?
document.querySelector('#info .service .fa-music').style.color = Music;
This one should also work:
document.querySelector('.fas.fa-music').style.color = Music;
It seems that you made a small mistake by writing ('.fas fa-music').
I am working on a personal project with a canvas that is a CSS grid. It is 17 rows and columns and instead of adding 289 divs manually, that I would create a for loop to do it for me when the page loads.
JavaScript:
var row = 1;
var column = 1;
function init() {
for (var i = 0; i < 289; i++) {
var div = document.createElement("div");
div.style.color = "gray";
div.style.gridRow = row;
div.style.gridColumn = column;
column += 1;
if (column == 17) {
row += 1;
column = 0;
}
console.log("test");
}
}
HTML:
<body onLoad="init();">
<canvas id="myCanvas" width="600" height="600"></canvas>
</body>
This is the only 'version' that I've tried that doesn't spit an error at me, but still nothing shows up. It runs though, because the console displays "test".
I've tried replacing:
var div = document.createElement("div");
with
var div = document.canvas.createElement("div");`,
var div = document.myCanvas.createElement("div");
...etc. (which probably aren't the right syntax but I tried them anyway) and it gives me this error when evaluating document.myCanvas.createElement:
TypeError: undefined is not an object
Basically I just want each grid box in the canvas to be filled using JS when the page loads. Also, I'm very new to programming so simple terms are much appreciated. Thank you in advance.
I ended up creating a div that had the canvas inside it and replacing:
var div = document.createElement("div");
with:
var newDiv = document.createElement("div");
document.getElementById("background").appendChild(newDiv);
and it worked great.
I want to edit my textarea manually after updating it with JavaScript, but when I write some text on it, the text I write is positioned over the text which is already in the textarea (written by JS).
So I'm searching of why can't I do it. Here is my code:
function initTextIA() {
var txt = document.createElement('textarea');
txt.style.rows = "5";
txt.style.cols = "45";
txt.style.top = "2300px";
txt.style.left = "250px";
txt.style.position = "absolute";
txt.style.background = "none";
txt.style.color = "green";
txt.id = "txtIA";
document.getElementById("cool").appendChild(txt);
}
initTextIA();
var doc = document.getElementById("txtIA")
doc.value += "txtxtxtxt.\n";
<div id="cool"></div>
The resulting HTML code of the textarea is :
<textarea id="txtIA" style="top: 2300px; left: 250px; position: absolute; background: none; color: green;"></textarea>
From comments it sounds to me like your line-height property is not properly set for textarea. Since you set textarea value with line break on the end:
txtxtxtxt.\n
newly written text should go in second row but it overlaps old text entered with JS. So try the following inside your initTextIA function:
txt.style.lineHeight = "2";
Since there is little original HTML provided in question so there are a lot of assumptions here. What I feel from all the discussion in comments is you are not able to append text then type in a value then continue appending it via some button.
I have written a simple case where I have commented out the positioning of textarea so testing can be done with ease. I have added two buttons but no error checks just to give a direction. Please let me know if this does not resolve the issue.
function initTextIA() {
var txt = document.createElement('textarea');
txt.style.rows = "5";
txt.style.cols = "45";
//txt.style.top = "2300px";
//txt.style.left = "250px";
//txt.style.position = "absolute";
txt.style.background = "none";
txt.style.color = "green";
txt.id = "txtIA";
document.getElementById("cool").appendChild(txt);
document.getElementById('addButton').style = 'display:none';
document.getElementById('appendButton').style = 'display:block';
}
function fillTextIA() {
var doc = document.getElementById("txtIA")
doc.value += "txtxtxtxt.\n";
}
<div>
<button id='addButton' onclick='initTextIA()'>add text area</button>
<button id='appendButton' onclick='fillTextIA()' style='display:none'>append text</button>
</div>
<div id='cool'>
<p>An element.</p>
</div>
Before I get in to this, I know I should learn jQuery but I haven't got to that yet, I want to learn raw JavaScript first! Well, mostly. Can someone help me without the use of jQuery please just for understanding, thank you!:
Hi, I'm new to JavaScript, not long started learning it as you can see by the first code (which works so I'm leaving it) for the navigation.
However, my problem comes on the 2nd piece of code I'm trying something from a different angle after watching videos on event listeners etc and everything I have written makes sense, to me, I'm going through it step by step, it's selecting all the right stuff, but it's still not showing the desired result!!
When you click CSS i want it to show the div with id "cs", and same for the HTML and JavaScript ones.
I really don't know JavaScript enough to solve this myself, I can not think of anything AT ALL to help with the problem!
Somebody save me, please, my mind is going crazy and I want to go to bed!
Here is the code, and here is the JS fiddle: https://jsfiddle.net/pmj26o9p/2/
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
switcheroo.onclick = function() {
if (switcheroo.style.display === "none") {
switcheroo.style.display = "";
} else {
switcheroo.style.display = "none";
}
}
EDIT: On reading through the code again I don't think it will achieve what I want even if it works. This will let me show and hide whichever I'm clicking right?
I want to show the clicked one but then hide / apply display:none to all others that aren't clicked.
My example below will show the chosen block and hide the others, as per your EDIT comment.
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
function contentShow(el) {
var whichOne = el.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
// show selected block, hide the others
switch (switcheroo) {
case htm:
htm.style.display = "block";
css.style.display = "none";
js.style.display = "none";
break;
case js:
htm.style.display = "none";
css.style.display = "none";
js.style.display = "block";
break;
case css:
htm.style.display = "none";
css.style.display = "block";
js.style.display = "none";
break;
}
}
<span data-id="htm" onClick="contentShow(this)" style="margin-right:10px;color:red; cursor:pointer">Click to show the HTML Block</span>
<span data-id="css" onClick="contentShow(this)" style="margin-right:10px;color:green; cursor:pointer">Click to show the CSS Block</span>
<span data-id="js" onClick="contentShow(this)" style="margin-right:10px;color:blue; cursor:pointer">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>
you are binding a second event handler to the switcheroo element, but the click event is not triggered so nothing happens.
If you want to make a toggle function on the switcheroo variable, you should do this instead:
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
return toggleDisplay(switcheroo);
}
function toggleDisplay(elem) {
if (elem.style.display === "none") {
elem.style.display = "";
} else {
elem.style.display = "none";
}
}
Ignoring your other bad practices, change
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
switcheroo.onclick = function() {
if (switcheroo.style.display === "none") {
switcheroo.style.display = "";
} else {
switcheroo.style.display = "none";
}
}
to something more like:
var doc = document;
function E(id){
return doc.getElementById(id); // you guessed it - same as document.getElementById, without typing it every time
}
var htm = E('htm'), css = E('css'), js = E('js');
contentShow = (function(){ // self-executing scopes off var showing - variable style assignment requires function definition before execution
var showing = false;
return function(){ // returns unexecuted function
var ht = E('ht').style, cs = E('cs').style, jsc = E('jsc').style;
if(showing){
ht.display = cs.display = jsc.display = 'none'; showing = false;
}
else{
ht.display = cs.display = jsc.display = 'block'; showing = true;
}
}
})();
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);
See updated JSFiddle here.
If there are no other click Events on those Elements, you could even change
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);
to
htm.onclick = css.onclick = js.onclick = contentShow;
JSFiddle here
but keep in mind this technique overwrites previous Events of the same type.
Here is a variation of #K Scandrett answer which add some scalability/flexibility
var navElements = document.getElementsByClassName("nav");
//Add Event Listeners
for(var i = 0; i < navElements.length; i ++)
{
navElements[i].addEventListener('click', contentShow, false);
}
function contentShow(el) {
var whichOne = el.target.attributes["data-id"].value;
var target = document.getElementById(whichOne);
for(var i = 0; i < navElements.length; i ++)
{
var content = document.getElementById(navElements[i].attributes["data-id"].value)
content.style.display = content === target ? "block" : "none";
}
}
<span data-id="htm" style="margin-right:10px;color:red; cursor:pointer" class="nav">Click to show the HTML Block</span>
<span data-id="css" style="margin-right:10px;color:green; cursor:pointer" class="nav">Click to show the CSS Block</span>
<span data-id="js" style="margin-right:10px;color:blue; cursor:pointer" class="nav">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>
I know you're looking for a javascript solution here.and kudos to you for wanting to understand javascript before getting into jquery, but here is an out of the box solution for you.... pure HTML and CSS
.info {display:none;}
.info:target{display:block;}
Click to show the HTML Block
Click to show the CSS Block
Click to show the JS Block
<br/>
<br/>
<div id="htm" class="info">Some HTML info here</div>
<div id="css" class="info">Some CSS info here</div>
<div id="js" class="info">Some JavaScript info here</div>
What I've done here is, leverage internal page id links and the :target selector. In my mind, this is more semantic and can also still be extended by scripting while still maintaining semantics. This option also gives your uses the option of bookmarking selections etc.
CSS OPTION 2
This option achieves the initial display. It is not as clean and uses absolute positioning and z-indexes. Alos note that is uses a background color to conceal the initial option.
.info {position:relative;}
.info > div {
position:absolute;
top:0;
left:0;
background-color:#FFF;
z-index:10;
display: none;
}
#htm
{
display:block;
z-index:1;
}
.info > div:target {
display: block;
}
Click to show the HTML Block
Click to show the CSS Block
Click to show the JS Block
<br/>
<br/>
<div class="info">
<div id="htm">Some HTML info here</div>
<div id="css">Some CSS info here</div>
<div id="js">Some JavaScript info here</div>
</div>
On a side note you should consider adding/removing css classes using javascript instead of the display property directly. This will enable the use of CSS transitions.
I need create a div above another div, but I dont have access to the css file, thus everything needs to be done via JavaScript.
This is my wrong code:
var div = document.getElementById("down");
var divAbove = document.createElement("div");
divAbove.id = "up";
divAbove.style.background = "red";
divAbove.style.position = "absolute";
divAbove.style.width = "150px"
div.appendChild(divAbove );
I can't see the new div.
If you can pinpoint the container element you can make use of .insertBefore()
More Info (docs)
var container = document.getElementById("container");
var div = document.getElementById("down");
var divAbove = document.createElement("div");
divAbove.id = "up";
divAbove.style.backgroundColor = "red";
divAbove.style.width = "110px"
divAbove.style.height = "60px"
divAbove.innerHTML = "Added via JS"
container.insertBefore(divAbove, div);
<div id='container'>
<div id='down' style='height: 60px; width: 110px; background-color: yellow'>
Existing element
</div>
</div>
This work.
var div = document.getElementById("down");
var divAbove=document.createElement("div");
divAbove.id = "up";
divAbove.style.background = "red";
divAbove.style.position = "absolute";
divAbove.style.width = "150px";
divAbove.style.height= "150px";
div.appendChild(divAbove);
From this point I would say that the div is there, but due to a typo in divAbov.style.background = "red"; it does not have a visible background. Try fixing the typo.
If the problem persists, please post your console log if there is any errors in there.
The reason you can't see new div is that you didn't give any body to it. For example, it may be a case to write before appending divAbove the following:
divAbove.innerHTML = "Hello World";