Child Div styles in javascript - javascript

I have got a preview box that gets the color and then changes it when the user does. However i have a child div that needs changine. how can i select the child div through get element by id?
this is the java script i have at the moment, how do i change this so i can get the child div front to change color
document.getElementById("flip3D").style.backgroundColor=p1;
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
}
#flip3D > .front{
... style stuff is all there just to much toput in and worry about
}

You mean something like this?
var front = document.querySelectorAll('#flip3D .front');
for(var i=0; i<front.length; i++){
front[i].style.backgroundColor = 'red';
}
or like:
var flipEl = document.getElementById("flip3D");
var frontEl = flipEl.getElementsByClassName('front');
for(var i=0; i<frontEl.length; i++){
frontEl[i].style.backgroundColor = p1;
}
Why not do it using CSS? (Your Question is pretty unclear so my hands are tied)

You could go with .childNodes() and .children() (Google will give you a lot of learning resources for these two methods. )
They will aid in selecting child elements within the DOM, of a specific element.

My first suggestion would be to use jQuery for this type of manipulation. It makes navigating the DOM and changing attributes much easier.
My second suggestion would be to control the color of both elements with a class. So your CSS might look something like this:
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
background: /*whatever you want the initial color to be*/;
}
#flip3D > .front {
/*Initial styling*/
}
#flip3D.stateChanged{
background: /*Whatever you want the new color to be*/;
}
#flip3D.stateChanged > .front {
/*New styling*/
}
Then in your Javascript you would change the class like this:
jQuery Example (using toggleClass):
jQuery('#flip3D').toggleClass('stateChanged');
You can also do the class manipulation in vanilla javascript but it is much messier. Something like this:
var ele = document.getElementById('#flip3D');
if(ele.className == 'stateChanged')
ele.className = '';
else
ele.className = 'stateChanged';

The simpleste way to do this is by using CSS. Change the background-color to inherit, that way they will allways have the color of their parent.
.child-node {
background-color: inherit;
}

Related

How do I change an attribute or class using only Javascript?

I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"
So the div element will look like the following:
<div class="post-feature" style="backgroundimage:url(http://local.test.com/test_image.jpg);">
So far the http check works. But I am not able to set the attribute value.
I have the following code
var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");
if (features.includes("http")) {
features.setAttribute("background-color", "orange");
} else {
alert('no change');
}
You can use querySelectorAll('.post-feature[style*="http"]') to find those elements.
Then simply iterate through them and i.e. set their background color with
element.style.backgroundColor = 'orange';
Now, if you want to make sure you only target elements having a background-image and http, you can use this selector:
querySelectorAll('.post-feature[style*="http"][style*="background-image"]')
Also, by adding an i (or I) just before the end bracket [style*="http"i], the value will be compared case-insensitively.
window.addEventListener('load', function() {
var elements = document.querySelectorAll('.post-feature[style*="http"]');
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = 'orange'; /* add propert value */
/* replace class
elements[i].className = 'myClass';
*/
/* add a class
elements[i].classList.add('myClass');
*/
}
/* temp log */
console.log('Found ', elements.length,' element(s)');
})
div {
height: 40px;
background-color: gray;
}
div + div {
margin-top: 10px;
}
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
Updated
To only change styling, like colors etc., you don't even need a script, you can use CSS alone
div {
height: 40px;
background-color: gray;
}
div + div {
margin-top: 10px;
}
/* for elements that contain "http" and "background-image" */
.post-feature[style*="http"i][style*="background-image"i] {
background-color: orange;
}
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
<div class="post-feature" style="background-image:url(HTTP://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
As a note, and as discussed in a few comments, if to make sure it is the background-image property that also contain the http in its url(), you can adjust the selector to this, which as well can be used without any script, as a CSS rule
.post-feature[style*="background-image:url(http"i] {
background-color: orange;
}
The above selector can of course also be used in the first sample, like this
querySelectorAll('.post-feature[style*="background-image:url(http"i]')
First, you can use querySelctorAll() with a CSS query that selects the elements with the class you desire and, in most cases, you should use this instead of getElementsByClassName() as that returns a "live node list" that causes the DOM to be re-scanned every time you access it.
Next, setAttribute() is for setting HTML element attributes. You are asking to change the value of a CSS property. While that could be accomplished with setAttribute('style', value), it is very "old-school" and not the best approach, nor is getAttribute('style') the best way to read a CSS property value (it won't work if the CSS was set from a style sheet).
Also, your code is trying to access: backgroundimage, but the property is accessed as background-image when working in CSS and backgroundImage when accessing it via JavaScript.
To access the inline styles applied to an HTML element, just access the style property of that element, followed by the name of the CSS property you are interested in. For example:
var bColor = element.style.backgroundColor;
If the style has been applied to the element from an internal style sheet or an external style sheet, the above approach won't work for you and you'll need to get it another way, via window.getComputedStyle():
var bColor = window.getComputedStyle(element, null).backgroundColor;
But, note that getComputedStyle() doesn't always return the same value that you set - - it's the value after the browser has computed all factors. In this case, even paths that you wrote as relative references (without the "http") will be returned as absolute paths (with the http).
So, here is a modern approach that correctly checks only the background-image CSS property for the presence of http.
NOTE: This solution tests for http specifically in the background-image property. Unlike most of the other answers given, this code will correctly ignore http in other CSS properties besides background-image. Examine the CSS of the last div to see this in action.
// querySelectorAll() is more efficient than getElementsByClassName()
var features = document.querySelectorAll(".post-feature");
// Loop over the list
for(var i = 0; i < features.length; i++){
// Get access to the background-image property (called backgroundImage from JavaScript) value,
// convert that value to lower case and check to see if "http" is in that value
if(features[i].style.backgroundImage.toLowerCase().indexOf("http") > -1){
// Set the CSS background-color property (called "backgroundColor" in JavaScript) to orange:
features[i].style.backgroundColor = "orange";
// Just for testing:
features[i].textContent = features[i].style.backgroundImage;
} else {
alert("No change");
}
}
.post-feature { width:100%; height:50px; border:1px solid black; background-color:gray; color:yellow; }
<!-- The correct CSS property is "background-image", not "backgroundimage" -->
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"
style="border-image: url('http:///images/border.png') 30 30 repeat;background-image:url(test_image.jpg);">I have "http" in one of my CSS properties, but not "background-image", so I shouldn't be orange.</div>
i think some wrong in your code, try this code
element.setAttribute("style", "background-color: orange;"); // bad
or
element.style.backgroundColor = "orange"; // good
Use element.style.backgroundColor and indexOf
var features = document.getElementsByClassName(".post-feature")[0].getAttribute("style");
if (features.indexOf("http") > -1) {
features.style.backgroundColor = "orange";
} else {
alert('no change');
}
check this fiddle
https://jsfiddle.net/vywk72j8/2/
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);">
tt</div>
var feature = document.getElementsByClassName("post-feature")[0];
if (feature.style.backgroundImage.indexOf("http") !== -1) {
feature.style.backgroundColor = "orange";
} else {
alert('no change');
}
In your code, you are fetching the attribute value in features
var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");
Here features is a string containing attribute value, not an element so you cannot use it to set value.

Get specific Inline CSS Style And Style Name

I'm looking for a way to get specific inline css styles from an element, including the style name itself and the value.
I have an element that contains different inline styles like so.
<div style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
I want to get the styles of that element(including the style name itself and value), but only the ones that have to do with "background" and ignore the others like "display, cursor, width"..etc
So to get the styles with jQuery I simply do this
$("div").attr("style");
That will return all the styles of the element including the ones I don't want. The solution I'm looking for would return something like this, which ignores the other styles that don't have to do with "background-"
background-color:red; background-size:cover; background-attachment:fixed; background-repeat:repeat-y;
I know I could get the individual styles like this
$("div").css("background");
$("div").css("background-size");
The problem with that is that it only gets the style value, and thats a problem because "background" could also be "background-image", or "background-repeat-y" could also be "background-repeat-x".
String manipulation is the wrong tool for this job, and I'm surprised that the other answers use it. The style element was designed for this task.
You can find a list of all inline styles by looking at element.style. The object looks like this:
You can see it contains each of the inline CSS rules separate from one another. Here is a very short live demo that prints this object to the console so you can see what I mean:
var el = document.getElementById("thediv");
console.log(el.style);
<div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
The object contains both an iterable list of rules (so for instance element.style[0] is background-color), as well as a dictionary so that you can get at specific rules by name. You should then be able to easily filter this list to get any specific rules you're looking for.
Here is a live demo that shows you how you can get all of the rules with the string background in them (open up the console). It puts the results into an array of name and value pairs that's easy to access:
var el = document.getElementById("thediv");
var result = [];
for (var i = 0; i < el.style.length; i++) {
if (el.style[i].indexOf("background") !== -1) {
result.push({name: el.style[i], value: el.style[el.style[i]]});
}
}
console.log(result);
<div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
You can do something like this:
$('div').each(function() {
style_arr=$(this).attr("style").split(';');
for(i=0;i<style_arr.length;i++) {
if(style_arr[i].indexOf('background')!=-1) {
console.log(style_arr[i]);
}
}
});
Demo: http://jsfiddle.net/sx3psqvh/
I'd do something like the following:
$(document).ready(function(){
var filteredStyles = $.grep($("div").attr("style").split(';'), function(style) {
return style.indexOf("background") > -1;
});
console.log(filteredStyles);
});
http://jsfiddle.net/6he3hu6y/
You could do it like this:
var style = $("div").attr("style");
var arrayStyle = style.split(';');
var backgroundStyles = '';
for (i = 0; i < arrayStyle.length; ++i) {
if (arrayStyle[i].indexOf("background") >= 0) {
backgroundStyles+=arrayStyle[i]+';';
}
}
console.log(backgroundStyles);
First of all, you get the whole style attribute,
then include all the CSS attributes splitting by the ";" into an array and finally for each key of the array looking for values containing "background". If so, just concat that value to a variable, adding ';' at the end of each value.

Replace "inline style" with a "css class" depending by value of its inline style

My site has CMS, so users can directly insert texts and images. CMS ui allows to float left/right images, applying an inline style to IMG tags.
<img src='...' style='float:left'>
I would like to detect when an IMG has a float:left/right style and replace it with a class in order to declare more properties for it like the following example:
.floated-left
{
float:left;
margin-right:20px;
border-left:solid 5px red;
....
}
I thought about something like this:
if ( $("article").find('img').css('float') == 'left')
{
this.addClass('floated-left');
}
But seems that "if clause" never be true. (I know that probably also this.addClass() is wrong, but neither alert() is never fired at the moment)
Can you help me?
Use attr instead of css for selecting inline styled objects:
$('article img').each(function() {
if ( $(this).attr('style') == 'float:left') {
$(this).removeAttr('style').addClass('floated-left');
}
});
if some of object's style is different, try this way:
$('article img').each(function() {
if ( $(this).attr('style').indexOf('float:left') > -1 ) {
var targetedStyle = $(this).attr('style').replace('float:left','');
$(this).attr('style',targetedStyle).addClass('floated-left');
}
});
In order to apply more declarations, you could simply achieve that by pure CSS:
img[style*="float:left"],
img[style*="float: left"] {
margin-right : 20px;
border-left : solid 5px red;
}
You could play with CSS attribute selectors to select the valid image/element.

Change :hover CSS properties with JavaScript

How can JavaScript change CSS :hover properties?
For example:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:
document.getElementsByTagName("td").style.background="#00ff00";
But I don't know of a .style JavaScript equivalent for :hover.
Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, #Bryan).
Pretty old question so I figured I'll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.
Taking the OP's example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here's a working example https://codepen.io/ybentz/pen/RwPoeqb
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on:
Change an element's class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\\s)' + oldClass + '(?!\\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
You can use mouse events to control like hover.
For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
Declare a global var:
var td
Then select your guiena pig <td> getting it by its id, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td's
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).
For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven't found any bugs in the functions;
After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
Had some same problems, used addEventListener for events "mousenter", "mouseleave":
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement.
DOMElement can be chosen by various ways.
I was researching about hover, to be able to implement them in the button label and make the hover effect
<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
#click="form1()">
Login
</button>
You can create a class in css
.hover:hover {
background: #ff0000;
}
and then add it dynamically
const columns = document.querySelectorAll('table td');
for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}
But your css and js files should be connected in index.html
const tds = document.querySelectorAll('td');
tds.forEach((td,index) => {
td.addEventListener("mouseover", ()=>hover(index))
td.addEventListener("mouseout", ()=>normal(index))
});
function hover(index){
tds[index].style.background="red";
}
function normal(index){
tds[index].style.background="yellow";
}
Try this code it will work fine .
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.

change a different div's class on mouseover

There's many examples of this but I can't find the right one for me - I believe mine is a more simple example.
I have as follows:
<li onmouseover="this.className='change-here2'" onmouseout="this.className='change-here'">
<div class="change-here">
Text Here
</div>
</li>
The li element has a background image, and a hover effect that changes the background image.
Using this.className changes the li class, when what I want is to change the div below it's class.
Shouldn't I be able to modify this to div.change-here, or something similar? I don't know the syntax...
Any help is appreciated.
EDIT: TimWolla's solution works brilliantly. Thank you all.
Why don't you use CSS only?
li .class { background-color: red; }
li:hover .class { background-color: green; }
See: http://jsfiddle.net/TimWolla/zp2td/
Can you do something to the affect of $(this).children(':first').addClass('change-here'); for that?
May I suggest:
var lis = document.getElementsByTagName('li');
for (var i=0, len=lis.length; i<len; i++){
lis[i].onmouseover = function(){
var firstDiv = this.getElementsByTagName('div')[0];
firstDiv.className = 'change-here';
};
lis[i].onmouseout = function(){
var firstDiv = this.getElementsByTagName('div')[0];
firstDiv.className = '';
};
}
JS Fiddle demo.
The reason I'm taking this approach, rather than using the in-line onmouseover attribute, is to make it somewhat easier to adapt in the case of the requirements changing at a later date. Also, it's slightly less 'intrusive' this way, and leaves the html somewhat easier to read. It is, of course a personal preference, though.
It's worth noting that the CSS-approach, as mentioned by TimWolla is far more sensible than involving JavaScript.
Updated answer to incorporate all the suggestions
<style>
.div_1 {
color: #F00;
}
.div_2 {
color: #0F0;
}
</style>
<li onMouseOver="this.childNodes[0].className = 'div_1';" onMouseOut="this.childNodes[0].className = 'div_2';">
<div class="div_1">
Text Here
</div>
</li>
This should work:
this.childNodes[0].className = 'change-here';

Categories