How do I change the CSS property display, in JavaScript, from display:none to display:normal for these divs?
#hide_0 { display:none }
#hide_1 { display:none }
#hide_2 { display:none }
#hide_3 { display:none }
#hide_4 { display:none }
#hide_5 { display:none }
Only one at a time. I need to display one and hide the rest.
What I used:
var persistent_element='hide_1';
function link_update(link_display)
{
var local_element;
local_element=document.getElementById(persistent_element);
local_element.style.display='none';
local_element=document.getElementById(link_display);
local_element.style.display='block';
persistent_element=link_display;
}
How I connected it : m4 is a minified - connects onclick to these methods
m4('l1',function {return link_update(hide_1);});
m4('l2',function {return link_update(hide_2);});
m4('l3',function {return link_update(hide_3);});
m4('l4',function {return link_update(hide_4);});
m4('l5',function {return link_update(hide_5);});
m4('l6',function {return link_update(hide_6);});
To use javascript to change the style, you can do it like this:
// hide an element
document.getElementById("hide_0").style.display = "none";
// show a block element
document.getElementById("hide_1").style.display = "block";
// to go back to the default or CSS specified value
document.getElementById("hide_2").style.display = "";
So, if you wanted to hide all and show one, you could do that with this function:
function showOneHideOthers(base, len, numToShow) {
// objects must have ids like base_0, base_1, etc...
for (var i = 0; i < len; i++) {
if (i != numToShow) {
document.getElementById(base+i).style.display = "none";
}
}
document.getElementById(base+numToShow).style.display = "block";
}
showOneHideOther("hide_", 6, 2);
P.S. normal is not a valid value for the display property. The typical values are block, none and inline and there are others like inline-block, table, etc....
Your question is not particularly clear, but the essence of what you want to do is simple. You can get a reference to a DOM element which has an id using getElementById, and you can change the display property:
document.getElementById("hide_0").style.display = "none"; //or "block"
However, you have several element that you want to hide/show (I'm not sure when you want to do so), so it may be easier to use a different method of selecting the elements (such as getElementsByTagName, or getElementsByClassName, but it depends on your HTML and what you're actually trying to do).
You can set a css property on an element using the style method.
div.style.display = '';
Related
my demo jsfiddle
What I want is a reverse transition when I click the < li > again, but the commentted code didn`t work,and the code below works fine
let dbclickre = true;
function flipped() {
if (dbclickre) {
document.querySelector(".linkrec").setAttribute("Id", "flipped");
} else {
document.querySelector(".linkrec").removeAttribute("Id", "flipped")
}
dbclickre = !dbclickre;
}
below is the commentted code (I think when i firstly click the last < li > ,js will excute the if statement(and indeed it works fine),but when i click again , the else statement didn't excude(but i have set #flipped .reverse {background: whitesmoke} ) . why this happening???)
// const dbclickre = document.querySelector(".reverse");
// function flipped() {
// if (dbclickre.style.backgroundColor = 'white') {
// document.querySelector(".linkrec").setAttribute("Id", "flipped");
// } else {
// document.querySelector(".linkrec").removeAttribute("Id", "flipped")
// }
// }
Instead of relying on background color for checking the state of flip, you could check for existence of Id attribute. Here the the changed code:
const dbclickre = document.querySelector(".reverse");
function flipped() {
if ( document.querySelector(".linkrec").getAttribute("Id") == undefined ) {
document.querySelector(".linkrec").setAttribute("Id", "flipped");
} else {
document.querySelector(".linkrec").removeAttribute("Id", "flipped")
}
}
Edit:
Why element.style would not work?
From MDN Web Docs:
The style property is used to get as well as set the inline style of an element.
Hence, the style property would not work with embedded or external CSS.
Also, it may not be a good idea to use hard-coded colors as the condition, because changing colors in the respective CSS classes would completely break the functionality.
Is it possible to change the styling of a psuedo :after element with javascript something like this:
document.querySelector('#test:after').attr("style", "content:url('blabla.png')");
Is there any workaround to change the image after 1 click like this:
var timesClicked = 0;
span = document.querySelector('.socialShare');
span.addEventListener('click', function (e) {
timesClicked++;
if (timesClicked > 1) {
document.querySelector('#socialShare').style.left = '-60px';
timesClicked = 0;
console.log(timesClicked)
} else {
document.querySelector('#socialShare').style.left = '0';
document.querySelector('#socialShare:after').attr("style", "content:url('blabla.png')");
console.log(timesClicked)
}
});
Or maybe better transform the image it is about an arrow which needs to point the other way when div is expanded
You can't change styles of pseudo elements with javascript, because they are not part of the DOM, and so do not have any API to work with.
Usual approach is to change classes of the element itself and have those classes affect related pseudo elements. For example in your case:
// Add class selected to element
document.querySelector('#test').classList.add('selected')
In CSS:
#test.selected::after {
content: url('blabla.png');
}
In css I have set all the <hr> elements in my html to "display:none;" which works.
I have an onclick event listener set up to change the "display" to "block".
I use:
document.getElementsByTagName("hr").innerHTML.style.display = "block";
I get an error "Cannot read property 'style' of undefined".
Do it the following way:
var hrItems = document.getElementsByTagName("hr");
for(var i = 0; i < hrItems.length; i++) {
hrItems[i].style.display = 'block';
}
This is incorrect in two ways
getElementsByTagName gives you a list on elements and there is no method to operate on all elements, so you'll have to loop through all of them and add the required style individually.
innerHTML returns a string containing the mark up in an element but <hr> doesn't have any thing in it and the style property is on the <hr> itself.
var hrs = document.getElementsByTagName("hr");
for(var i = 0; i < hrs.length; i++) {
hrs[i].style.display = 'block';
}
Simple (and very effective) solution:
tag your body with a class-element
<body class="no_hr"> <article><hr/> TEXT Foo</article> <hr/> </body>
in css don't hide hr directly, but do
.no_hr hr {
display:none;
}
now define a second style in your css
.block_hr hr{
display:block;
}
in your buttons onClick, change the one and only body class from no_hr to block_hr
onclick() {
if ( document.body.className == "no_hr" ) {
document.body.className = "block_hr";
} else {
document.body.className = "no_hr";
}
}
This is a very charming solution, because you don't have to iterate over elements yourself, but let your browsers optimized procedures do their job.
For people who want a solution that doesn't require JavaScript.
Create an invisible checkbox at the top of the document and make sure that people can click on it.
<input type="checkbox" id="ruler"/>
<label for="ruler">Click to show or hide the rules</label>
Then tell the stylesheet that the <hr>s should be hidden by default, but should be visible if the checkbox is checked.
#ruler, hr {display:none}
#ruler:checked ~ hr {display:block}
Done. See fiddle.
getElementsByTagName() returns a node list, and therefore you must iterate through all the results. Additionally, there is no innerHTML property of an <hr> tag, and the style must be set directly on the tag.
I like writing these types of iterations using Array.forEach() and call:
[].forEach.call(document.getElementsByTagName("hr"), function(item) {
item.style.display = "block";
});
Or, make it even easier on yourself and use jQuery:
$("hr").show();
I would like to use JavaScript to manipulate my CSS. First it was just thought to be a nice little script to try out different colors for my accordion menu together with different backgrounds/title-/content-/... background-colors from an input field.
I understand how I get the input value with js.
I understand how CSS is manipulated by using getElementById(), getElementsByClassName(), getElementsByTag(), and getElementsByName().
Now, the problem is that my CSS looks like this:
.accordion li > a {
/* some css here */
}
.sub-menu li a {
/* some css here */
}
.some-class hover:a {
/* css */
}
.some-other-class > li > a.active {
/* css */
}
How would I change the properties of such stylings with JavaScript?
There's no way to manipulate some CSS styles directly with JavaScript. Instead you can change a rule in a stylesheet itself, something like this:
var changeRule = function(selector, property, value) {
var styles = document.styleSheets,
n, sheet, rules, m, done = false;
selector = selector.toLowerCase();
for(n = 0; n < styles.length; n++) {
sheet = styles[n];
rules = sheet.cssRules || sheet.rules;
for(m = 0; m < rules.length; m++) {
if (rules[m].selectorText.toLowerCase() === selector) {
done = true;
rules[m].style[property] = value;
break;
}
}
if (done) {
break;
}
}
};
changeRule('div:hover', 'background', '#0f0');
selector must match exactly an exisiting selector, only spaces between selector text and { are ignored.
You can develope the code to find and change partial hits of selector names, or just check a particular stylesheet instead of all of them. As it is, it's also quite expensive when having tens of stylesheets with thousands of rules.
Unfortenately pseudo elements can't be manipulated with this snippet.
A live demo at jsFiddle.
All DOM elements have a style object that can be altered by JavaScript
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style?redirectlocale=en-US&redirectslug=Web%2FAPI%2Felement.style
Or if you're using jQuery:
http://api.jquery.com/css/
You can target elements and manipulate their propertoes, but you do not alter the rules.
A common approach if you want to alter large numbers of style properties is to alter elements' class names to change their appearance. This can be done with the className property, or if you're using jQuery: addClass and removeClass.
I've implemented Teemu's answer with underscore. http://jsfiddle.net/6pj3g/4/
var rule = _.chain(document.styleSheets)
.map(function(sheet){return _.flatten(sheet.cssRules)})
.flatten()
.unique()
.find(function(rule){ return rule && rule.selectorText && (rule.selectorText.toLowerCase() === selector.toLowerCase())})
.value()
if (rule){
rule.style[property] = value;
} else {
throw 'selector not found: ' + selector;
}
i have a same question asked here(wasnt able to comment on it,maybe dont have a priviledge) , i want to get css width value defined in stylesheet but not yet applied on any element in dom ,(its bootstrap css with grid with responsive media queries)
.span6 {
width: 570px;
}
However solution provided in above referenced question return 0 i.e like this
$('<div/>').addClass('span6').width();
but works if i do something like this
$('<div/>').addClass('span6').hide().appendTo('body').width();
any easy way without appending that div?
In order to read a CSS property value from a nonexistent element, you need to dynamically insert that element (as hidden) to the DOM, read the property and finally remove it:
var getCSS = function (prop, fromClass) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
$("body").append($inspector); // add to DOM, in order to read the CSS property
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};
jsFiddle here
Great answer by Jose. I modified it to help with more complex css selectors.
var getCSS2 = function (prop, fromClass, $sibling) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
if($sibling != null){
$sibling.after($inspector); //append after sibling in order to have exact
} else {
$("body").append($inspector); // add to DOM, in order to read the CSS property
}
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};
JSFiddle