Change Properties of Items using a forEach Method (javascript) - javascript

I'm using a javascript forEach method to iterate over items in an array, but it's throwing an error when I try and do something with the items.
In the code below when I console log 'item' it gives the desired behavior of logging 'div1, div2, div3' to the console. However, when I try and make a change to these items it won't allow it. The examples of using a forEach method in JS when you Google it is very abstract.
How do I use this method to change the background colors or other properties of the items?
Codepen link is here https://codepen.io/emilychews/pen/boJBKB
JS
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = ['div1','div2','div3']
myArray.forEach(function(item){
console.log(item);
item.style.backgroundColor = "blue";
})
CSS
.div {height: 50px; width: 50px; background-color: red; margin-bottom: 10px;}
HTML
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>
Any help would be awesome
Emily

Remove the quotes like: var myArray = [div1,div2,div3]

your myArray contains Strings, not Dom Nodes.
try this code:
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = [div1,div2,div3]
myArray.forEach(function(item){
console.log(item);
item.style.backgroundColor = "blue";
})

Related

Get CSS position property of element with JavaScript

For example I have this <div> with the following CSS:
.some-div{
position: relative;
top: 50px;
}
<div class="some-div">
<p>Some content</p>
</div>
How do I get the CSS property position of the element with JavaScript (which in this example should result in the string "relative")?
Window.getComputedStyle()
The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain
const element = document.getElementById('your_element_id');
const computedStyles = getComputedStyle(element);
const position = computedStyles.position;
Assuming your "class" has only one element:
HTML
<div class="some-div"">
<p>Some text</p>
</div>
JAVASCRIPT
let someDiv = document.getElementsByClassName('some-div')[0];
someDiv.addEventListener('click', () => {
console.log(this.getComputedStyle(someDiv).getPropertyValue('position'));
});
var element = document.querySelector('.some-div');
var style = window.getComputedStyle(element);
var pos = style.position;
console.log(pos);
Try this.
The Console output must be: "relative"

append css inline styles in js button for hover [duplicate]

I've created the following...
var menu = document.createElement('select');
How would I now set CSS attributes e.g width: 100px?
Use element.style:
var element = document.createElement('select');
element.style.width = "100px";
Just set the style:
var menu = document.createElement("select");
menu.style.width = "100px";
Or if you like, you can use jQuery:
$(menu).css("width", "100px");
For most styles do this:
var obj = document.createElement('select');
obj.style.width= "100px";
For styles that have hyphens in the name do this instead:
var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"
That's actually quite simple with vanilla JavaScript:
menu.style.width = "100px";
Just for people who want to do the same thing in 2018
You can assign a CSS custom property to your element (through CSS or JS) and change it:
Assigment through CSS:
element {
--element-width: 300px;
width: var(--element-width, 100%);
}
Assignment through JS
ELEMENT.style.setProperty('--element-width', NEW_VALUE);
Get property value through JS
ELEMENT.style.getPropertyValue('--element-width');
Here useful links:
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty
All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.
Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.
In prototype I would do:
$(newElement).addClassName('blah')
When debugging, I like to be able to add a bunch of css attributes in one line:
menu.style.cssText = 'width: 100px';
Getting used to this style you can add a bunch of css in one line like so:
menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';
if you want to add a global property, you can use:
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
<h1>Silence and Smile</h1>
<input type="button" value="Show Red" onclick="document.getElementById('h1').style.color='Red'"/>
<input type="button" value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>
This works well with most CSS properties if there are no hyphens in them.
var element = document.createElement('select');
element.style.width = "100px";
For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase
var element = document.createElement('select');
element.style.maxWidth = "100px";
<body>
<h1 id="h1">Silence and Smile</h1><br />
<h3 id="h3">Silence and Smile</h3>
<script type="text/javascript">
document.getElementById("h1").style.color = "Red";
document.getElementById("h1").style.background = "Green";
document.getElementById("h3").style.fontSize = "larger" ;
document.getElementById("h3").style.fontFamily = "Arial";
</script>
</body>

jQuery nest appends

is it possible to nest appends in jQuery??
I tried to do this:
var div = $('#ui-container');
var div2 = div.append( $('<div/>').addClass('second') );
var div3 = div2.append( $('<div/>').addClass('third') );
I want this:
<div id='ui-container'>
<div class='second'>
<div class='third'></div>
</div>
</div>
But I get this:
<div id='ui-container'>
<div class='second'></div>
<div class='third'></div>
</div>
You have to do it like below,
var div = $('#ui-container');
var div2 = $('<div/>').addClass('second').appendTo(div);
var div3 = div2.append($('<div/>').addClass('third'));
by using .appendTo(). Because .append() will return the object over which the append function was called. That is why you are seeing such result in your case.
#Rajaprabhu Aravindasamy has the correct answer. I thought I would go a little more in depth and add a jsfiddle.
Use appendTo() instead of append. Here's a quote from http://api.jquery.com/appendto/
The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.
Here's the markup:
var div = $('#ui-container');
var div2 = $('<div>div2<div/>').addClass('second').appendTo(div);
var div3 = $('<div>div3<div/>').addClass('third').appendTo(div2);
Try:
var div = $('#ui-container');
var div2 = $('<div/>').addClass('second');
div2.append( $('<div/>').addClass('third') );
div.append(div2);
jquery methods typically return the DOM node that they are being called on.
Therefore
var div2 = div.append( $('<div/>').addClass('second') ); // returns $('#ui-container')
It is also standard to reference DOM elements with a $ such as $div.
Here is a verbose solution
// Grab container
$div = $('#ui-container');
// Create first child
var div2 = '<div class="second"></div>'
// Append .second to #ui-container
$div.append(div2);
// Grab .second from the DOM
var $div2 = $('.second');
// Create grandchild element
var div3 = '<div class="third"></div>'
// Append to .second
$div2.append(div3)
codepen
All of your variables div, div2 and div3 refer to the same element $('#ui-container'). Easiest way to understand what you did would be to rename your variables, so you can see what happens:
/* What you did is this: */
var container = $('.result1');
var containerWithSecondAppended = container.append( $('<div/>').addClass('second') );
var containerWithThirdAppended = containerWithSecondAppended.append( $('<div/>').addClass('third') );
/* What you wanted to do is this: */
var div = $('.result2');
var div2 = $('<div/>').addClass('second');
var div3 = $('<div/>').addClass('third');
div.append( div2.append(div3) );
div {
padding: 10px;
border: 1px solid black;
}
.result {
margin: 10px;
padding: 10px;
}
.second {
background: none yellow;
}
.third {
background: none green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result result1"></div>
<div class="result result2"></div>
Also on Fiddle.
jQuery append method will return a jQuery element, the one that was appended (changed).

How to get Element from Node

From my understanding, document.querySelector returns a Node object. I can then call appendChild on this object.
I execute the following code to append a bunch of divs to my container div:
var container = document.querySelector('.container');
for (var i = 0; i < 400; i++) {
var block = document.createElement('div');
block.className = 'block';
container.appendChild(block);
}
And end up with the following structure:
<div class="container">
<div class="block"></div>
<div class="block"></div>
...
<div class="block"></div>
</div>
How can I loop through each element in my container div and add a new class to it using my existing container variable?
I have tried this:
...
container.childNodes[i].className = 'myClass';
It seems I need to access the Element object of the child Node, but I'm not sure how to do this.
Can you not just add it when you create the divs ?
var container = document.querySelector('.container');
for (var i = 0; i < 400; i++) {
var block = document.createElement('div');
block.className = 'block myClass';
container.appendChild(block);
}
To add classes to the elements in the container variable, I used the following code:
container.children[i].className = 'myClass';
I had to use children instead of childNodes. You can see the context in which this code was used here: http://codepen.io/robkom/pen/RWmodz.

Getting infinity loop when I append div to existing divs?

I had took some program test online,from there I got some infinity loop error in appending new div to existing div.
<div id="one">
<div id="two"></div>
</div>
And this JS code is to add new div:
appendChildren();
function appendChildren() {
var allDivs = document.getElementsByTagName("div");
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
}
I want the HTML to look like this:
<div id="one">
<div id="two">
<div></div>
</div>
<div></div>
</div>
But at run time the program doesn't stop looping. Why? I couldn't guess! So can I run that appendChildren() only one time or is there another solution?
document.getElementsByTagName("div") is a live collection - it always reflects the actual data.
It means that when you append a div item, it is automatically appended to your collection. So, it never ends.
You can copy your collection using [].slice.call so that it doesn't change.
Here is the working demo snippet:
function appendChildren() {
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
}
appendChildren();
// For demonstration purposes only:
document.getElementById('html').innerText = document.getElementById('one').outerHTML;
<div id="one">
<div id="two">
</div>
</div>
<pre id="html"></pre>
The html element displays the HTML result - however, it looks bad. You may use developer tools to see the actual structure in a familiar way.

Categories

Resources