How to get elements with certain style - javascript

So say I have this in my body:
<body>
<h1>Hello world!</h1>
<h2 style="color: Blue;">This is my webpage</h2>
<a style="color: Blue;" onClick="changeElem();">Welcome!</a><br>
<h3>Goodbye</h3>
</body>
I want to create function changeElem() such that it will change the content that is blue to black. So this is the result I want to get after using this function:
<h1>Hello world!</h1>
<h2 style="color: Black;">This is my webpage</h2>
<a style="color: Black;" onClick="changeElem();">Welcome!</a><br>
<h3>Goodbye</h3>
How can this be done?

You're much better off doing this with CSS, not inline styles.
<head>
<style>
/* By default, elements with class="some-class" are blue */
.some-class {
color: blue;
}
/* But if body has the class "updated", they turn black */
body.updated .some-class {
color: black;
}
</style>
<h1>Hello world!</h1>
<h2 class="some-class">This is my webpage</h2>
<a class="some-class" onClick="changeElem();">Welcome!</a><br>
<h3>Goodbye</h3>
</body>
...where changeElem is:
function changeElem() {
document.body.className += " updated";
}
Live Example | Live Source
If you're dead set on using inline styles, which is not a good idea, you can still do it easily enough:
function changeElem() {
var div, colorValue, list, index, element;
// Figure out what this browser returns for `color: Blue`
// (it might be "Blue", "blue", "rgb(0, 0, 255)",
// "rgba(0, 0, 255, 0)", "#0000FF", "#0000ff",
// or possibly others)
div = document.createElement('div');
document.body.appendChild(div);
div.innerHTML = '<span style="color: Blue;"></span>';
colorValue = div.firstChild.style.color;
document.body.removeChild(div);
// Get list of all elements that have any `style` attribute at all
list = document.querySelectorAll('[style]');
// Loop through looking for our target color
for (index = 0; index < list.length; ++index) {
element = list[index];
if (element.style.color === colorValue) {
element.style.color = "black";
}
}
}
Live Example | Live Source

I suggest working with Class Selectors.
<body onLoad="getElem();">
<h1>Hello world!</h1>
<h2 class="blue">This is my webpage</h2>
<a class="blue">Welcome!</a><br>
<h3>Goodbye</h3>
</body>
Then you could easily select all Elements with a common class via document.querySelectorAll():
document.querySelectorAll(".blue")
for all Elements with the class blue (e.g.)
Then you could set the class of each element simply to black.

function getElem(){
var items = document.body.getElementsByTagName("*");
for (var i = items.length; i--;) {
style = window.getComputedStyle(items[i].innerHTML);
color = style.getPropertyValue('color');
if(color =="rgb(0,0,255)"){
items[i].style.color="black";
}
}
}

Related

display different comand and result from getElementsByClassName() Method

i just wanna ask how to change or display the different color with "getElementsByClassName() Method" in javascript,so here i want to change the bacground color blue from class "ex",and color red form class "example",but it doesnt work.
<!DOCTYPE html>
<html>
<head>
<style>
.example {
border: 1px solid black;
padding 8px;
}
</style>
</head>
<body>
<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>
<p>Change the background color of all elements with class="example":</p>
<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="example"
</div>
<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="example".
</p>
<p>A <span class="example">span</span> element with class="example".</p>
<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
const collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "blue";
}
</script>
</body>
</html>
your code works fine but you had two variables with the name collection rename one of them
<!DOCTYPE html>
<html>
<head>
<style>
.example {
border: 1px solid black;
padding 8px;
}
</style>
</head>
<body>
<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>
<p>Change the background color of all elements with class="example":</p>
<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="example"
</div>
<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="example".
</p>
<p>A <span class="example">span</span> element with class="example".</p>
<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
const collection2 = document.getElementsByClassName("ex");
for (let i = 0; i < collection2.length; i++) {
collection2[i].style.backgroundColor = "blue";
}
</script>
</body>
</html>
What does "doesn't work" mean? Is ex blue, and example uncolored? Are none colored?
Try checking the output in console (Developer tools - F12). I am certain you will receive an error using your snippet, as you redefine the collection variable twice. Use let instead of const if you plan on using a solution which changes a variable's value after assignment. Alternatively, define another variable for your second for-loop.
Here's your snippet corrected if you're still not sure:
let collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "blue";
}

how to get the <a>under the <p>

I'm trying to get the a tag under the specific p tag.
I have tried this but is not working. I am trying to change the CSS style of the link part to red color and came with a red dot line when hovering the line will become solid.
var font_8 = document.getElementsByClassName('font_8');var elements = font_8.getElementsByTagName('a');
html:
<p class="font_7" style="font-size:16px">text text text text<br>
<span style="text-decoration:underline">link link link</span>(text)</p>
<p class="font_8" style="font-size:16px">text text text text<br>
<span style="text-decoration:underline">link link link</span>(text)</p>
js:
<script>
const styles = {
textDecoration: 'none',
color: 'red',
borderBottom: '2px dotted currentColor',
}
function getElements() {
var font_8 = document.getElementsByClassName('font_8');var elements = font_8.getElementsByTagName('a');
var len = elements.length;
for (let i = 0; i < len; i++) {
Object.keys(styles).forEach((key)=>{
elements[i].style[key]=styles[key]
})
}
for (let i = 0; i < len; i++){
elements[i].addEventListener('mouseover', function() {
elements[i].style.borderBottom= '2px solid currentColor';
})
elements[i].addEventListener('mouseout', function() {
Object.keys(styles).forEach((key)=>{
elements[i].style[key]=styles[key]
})
})
}
}
getElements()
</script>
Using JavaScript just to learn, this is my solution with a query selector:
const styles = {
textDecoration: 'none',
color: 'red',
borderBottom: '2px dotted currentColor',
}
const normalStyle = 'dotted'
const hoverStyle = 'solid'
function applyStylesAndHover() {
// querySelectorAll allows you to basically use a CSS selector in your JS
const elements = document.querySelectorAll('.font_8 a');
elements.forEach((element) => {
Object.keys(styles).forEach((key) => {
element.style[key] = styles[key]
})
element.addEventListener('mouseover', function() {
element.style.borderBottomStyle = normalStyle;
})
element.addEventListener('mouseout', function() {
element.style.borderBottomStyle = hoverStyle;
})
})
}
applyStylesAndHover()
<p class="font_7" style="font-size:16px">
text text text text
<br>
<span style="text-decoration:underline">
link
</span>(text)
</p>
<p class="font_8" style="font-size:16px">
text text text text
<br>
<span>
link
</span>(text)
</p>
Although To style the <a> on hover you do not need JavaScript.
CSS is perfect for this:
.font_8 a { /* An <a> inside of an element with the class of font_8 */
color: red;
text-decoration: none;
border-bottom: 2px solid red;
}
.font_8 a:hover { /* An <a> that is being hovered inside of an element with the class of font_8 */
border-bottom-style: dotted;
}
<p class="font_7" style="font-size:16px">
text text text text
<br>
<span style="text-decoration:underline">
link
</span>(text)
</p>
<p class="font_8" style="font-size:16px">
text text text text
<br>
<span>
link
</span>(text)
</p>
One problem i found here is you are tring to get <a> using font_8.getElementsByTagName('a'); which will not work. u will need to assign id to the a tag and get it by using
var element = document..getElementsById('myAncor');
and To move it inside p tag u will need to append the element to font_8 using .appenChild().
edit:
sry i misunderstood ur question.
to do this with JS use
var element= font_8[0].children[1].children[0];
element.addEventListener(
// your core
)
or
var elements= document.querySelectorAll('.font_8 a');
//Your code
elements[i].addEventListener(
// your core
)

CSS & JS change div background-color on button hover?

For my Website, I have a set background-color of the div class "coverbg", for example
cover{
background-color: #FFFFFF;
}
I also have a button defined in the .html-File (Let's say it has the ID "triggerbg"), and I want the Background-Color of the div to change (to for example #000000;) when the button is being hovered over with a mouse and change back when the mouse isn't on the button anymore. Is there a way to do this?
I also tried a code from stackoverflow, I tried replacing "body" with div class "cover" but it is not working,
var button = document.getElementById('hover');
var body = document.body;
button.onmouseover = function() {
body.className = 'hovered';
}
button.onmouseout = function() {
body.className = '';
}
body {
background: #000;
}
body.hovered {
background: #ff0;
}
<button id="hover">button</button>
Sorry, I am new to JS.
if you want to change the body background
modifying Ran Turner's post you get
function over(){
document.getElementsByTagName("BODY")[0].className = 'hovered';
}
function out(){
document.getElementsByTagName("BODY")[0].className = ' '
}
.hovered{
background:#000000;
}
<html>
<head></head>
<body>
<button onmouseover="over()" onmouseout="out()">hover</button>
</body>
</html>
or if you want a div
var trigger=document.getElementById("triggerbg");
var cover=document.getElementsByClassName("cover");
trigger.onmouseover=function(){
for (var i = cover.length-1; i >= 0; i--) {
cover[i].className="hovered";
}
cover=document.getElementsByClassName("hovered");
}
trigger.onmouseout=function(){
for (var i = cover.length-1; i >= 0; i--) {
cover[i].className="cover";
}
cover=document.getElementsByClassName("cover");
}
.cover{
background-color:yellow;
}
.hovered{
background-color:#000000;
}
<button id="triggerbg">hover</button>
<div class="cover">here</div>
<div class="cover">there</div>
<div class="cover">and</div>
<div class="cover">everywhere</div>
You also need to get the div element and on onmouseover/onmouseout events add/remove the class from that div respectively
var button = document.getElementById('hover');
var div = document.getElementById('your-div');
button.onmouseover = function() {
div.className = 'hovered';
}
button.onmouseout = function() {
div.className = '';
}
.hovered{
background-color: #000000;
}
<button id="hover">button</button>
<div id="your-div">
hover button to change color
</div>
In this Code, onmouseover and onmouseout event is used to change the class of div.
<html lang="en">
<head>
<title>Document</title>
<style>
/* hover class to change the background when hover on button */
.hover{
background-color:#aaaaaa
/* color=red */
}
</style>
</head>
<body>
<button id="hover" class="demo">button</button>
<div id='div' >Hover on button to see the effect on div</div>
<script>
let button = document.getElementById('hover');
let div = document.getElementById('div');
button.onmouseover = () =>{ // onmouseover event which executes when the mouse hover on element button
div.className ='hover'; // change the class name of div
}
button.onmouseout = () =>{
div.className ='';
}
</script>
</body>
</html>
Here is the code snippet you use to change the background of a button on the mouse hover.
In this Code, we use the hover property of a class that changes the background of a button when hover. You can use the style in your external CSS file or internal CSS in the HTML file in the tag.
<html lang="en">
<head>
<title>Document</title>
<style>
.demo:hover{
background-color: #FFFFFF;
}
</style>
</head>
<body>
<button id="hover" class="demo">button</button>
</body>
</html>

HTML Dark Mode With Pure JavaScript

I'd like to add dark mode to my website with javascript. It works technically, but not the way I wanted it to. It only set the body color to black. But the challange is to set color to the "< div >" tags. Honestly I don't really know JavaScript, so I don't know how to do it.
Here is my code:
document.body.style.backgroundColor = sessionStorage.getItem('bg');
document.body.style.color = sessionStorage.getItem('cc');
document.div.style.backgroundColor = sessionStorage.getItem('cardbg');
document.div.style.color = sessionStorage.getItem('cardcc');
function darker() {
if ( sessionStorage.getItem('bg') === 'rgb(241, 241, 241)') {
sessionStorage.setItem('bg', 'rgb(6, 23, 37)');
sessionStorage.setItem('cc', '#fff');
sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
sessionStorage.setItem('cardcc', '#fff');
}
else if (sessionStorage.getItem('bg') == null || undefined) {
sessionStorage.setItem('bg', 'rgb(6, 23, 37)');
sessionStorage.setItem('cc', '#000');
sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
sessionStorage.setItem('cardcc', '#fff');
}
else if( sessionStorage.getItem('bg') === 'rgb(6, 23, 37)') {
sessionStorage.setItem('bg', 'rgb(241, 241, 241)');
sessionStorage.setItem('cc', '#000');
sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
sessionStorage.setItem('cardcc', '#fff');
}
document.body.style.backgroundColor = sessionStorage.getItem('bg');
document.body.style.color = sessionStorage.getItem('cc');
document.div.style.backgroundColor = sessionStorage.getItem('cardbg');
document.div.style.color = sessionStorage.getItem('cardcc');
}
<html>
<head>
<style>
body {
background-color: #f1f1f1;
color: #000;
}
.card {
background-color: red;
color: black;
}
</style>
</head>
<body>
<div class="card">
<h5>Title</h5>
<p>Some text...</p>
<p>Another text..</p>
</div>
</body>
<script src="assets/js/darker.js"></script>
</html>
You could store your themes in an object and switch them during runtime using document.documentElement.style.setProperty()
Example:
const dark = {
'background-color': '#FFFFFF'
}
const light = {
'background-color': '#000000'
}
In your CSS (Note: to only style div's use body > div)
--background-color: #000000 // this is the default
body > div {
background-color: var(--background-color);
}
And finally if you need to switch the theme you can do:
function setTheme(a_oTheme) {
Object.keys(a_oTheme).forEach(k =>
document.documentElement.style.setProperty(`--${k}`, a_oTheme[k])
);
}

Javascript if and else runs simultaneously

I want a link to select by onclick, when the link is clicked so selected, the background should change. When I click the selected link again then the background should be transparent again.
My Script:
<div style="background: transparent;" onclick="click()" id="0">
HTML:
Click
function click() {
var click = document.getElementById("0");
if(click.style.background == "transparent") {
click.style.background = "red";
}
else {
click.style.background = "transparent";
}
}
As far as I understand, you simply want a toggle. Functional code as follows.
2 important notes:
ID must not be zero (or it breaks): I replaced it by 10;
don't use click() as it's a reserved name: I replaced it by toggle().
Not much change to your code apart from the above.
Cheers.
Update to handle multiple divs: I now pass the object:
<html>
<body>
<div style="background: red;" onclick="toggle(this)" id="10">
CLICK ON 10 TO TOGGLE MY BACKGROUND COLOR
</div>
<div style="background: red;" onclick="toggle(this)" id="20">
CLICK ON 20 TO TOGGLE MY BACKGROUND COLOR
</div>
<script>
function toggle(o) {
if(o.style.background == "transparent") {
o.style.background = "red";
alert("red on "+o.id);
}
else {
o.style.background = "transparent";
alert("transparent on "+o.id);
}
}
</script>
</body>
</html>
Two things here, don't call the function click, and use the backgroundColor property, not background as background is a compound property expecting more values than just the color, so comparing it to just a color (i.e. = 'transparent") may not work
so
HTML:
<div style="background-color: transparent;" onclick="notclick()" id="0">
Javascript
function notclick() {
var click = document.getElementById("0");
if(click.style.backgroundColor == "transparent") {
click.style.backgroundColor = "red";
}
else {
click.style.backgroundColor = "transparent";
}
}
EDIT
to handle mutliple div
every div that you want the behaviour, should be like this (i.e. with the onclick(this))
<div style="background-color: transparent;" onclick="notclick(this)" id="0">
<div style="background-color: transparent;" onclick="notclick(this)" id="1">
<div style="background-color: transparent;" onclick="notclick(this)" id="2">
and the javascript should be
function notclick(ele) {
if(ele.style.backgroundColor == "transparent") {
ele.style.backgroundColor = "red";
}
else {
ele.style.backgroundColor = "transparent";
}
}
or better still
function notclick(ele) {
ele.style.backgroundColor = (ele.style.backgroundColor == "transparent" ? "red" :"transparent");
}
The problem is the method name click, inside the onclick handler it refers to the internal click method - fiddle - here click is a native method, not our method
Rename it and it should be fine - you need to use backgroundColor
<button onclick="testme()">Test</button>
then
function testme() {
var click = document.getElementById("0");
if (click.style.background == "red") {
click.style.background = "transparent";
} else {
click.style.background = "red";
}
}
Demo: Fiddle

Categories