I created 3 radio buttons and a label for each of them using JavaScript. When I try adding for in the label using htmlFor, it doesn't apply it to the actual DOM Element. Meaning, when I try using the label on the webpage, it doesn't select the radio button.
I checked in the developer tools, and saw that the labels did not have for applied to them.
What am I doing wrong, and how can I fix it?
JSFiddle
var _doc = document,
sliderWrapper = _doc.getElementById('sliderWrapper'),
radioWrapper = _doc.createElement('div');
for (var i = 0; i < 3; i++) {
var radio = _doc.createElement('input');
var niceRadio = _doc.createElement('lable');
var index = radioWrapper.children.length / 2;
niceRadio.className = 'niceRadio';
niceRadio.htmlFor = radio.id = 'sliderRadio' + index;
radio.type = 'radio';
radio.name = 'myName';
radioWrapper.appendChild(radio);
radioWrapper.appendChild(niceRadio);
console.log(niceRadio.htmlFor);
}
sliderWrapper.appendChild(radioWrapper);
.niceRadio {
position: relative;
width: 20px;
height: 20px;
cursor: pointer;
border-radius: 50%;
border: 5px solid orange;
}
.niceRadio:hover {
border-color: lightblue;
}
<div id="sliderWrapper">
</div>
The htmlFor is used to bind a label to a specific form element. However, it uses the id of that form element (not the name).
Source MDN:
The HTMLLabelElement.htmlFor property reflects the value of the for
content property. That means that this script-accessible property is
used to set and read the value of the content property for, which is
the ID of the label's associated control element.
Also, in your fiddle, you misspelled label.
Updated fiddle: https://jsfiddle.net/h09mm827/2/
Related
I created 3 radio buttons and a label for each of them using JavaScript. When I try adding for in the label using htmlFor, it doesn't apply it to the actual DOM Element. Meaning, when I try using the label on the webpage, it doesn't select the radio button.
I checked in the developer tools, and saw that the labels did not have for applied to them.
What am I doing wrong, and how can I fix it?
JSFiddle
var _doc = document,
sliderWrapper = _doc.getElementById('sliderWrapper'),
radioWrapper = _doc.createElement('div');
for (var i = 0; i < 3; i++) {
var radio = _doc.createElement('input');
var niceRadio = _doc.createElement('lable');
var index = radioWrapper.children.length / 2;
niceRadio.className = 'niceRadio';
niceRadio.htmlFor = radio.id = 'sliderRadio' + index;
radio.type = 'radio';
radio.name = 'myName';
radioWrapper.appendChild(radio);
radioWrapper.appendChild(niceRadio);
console.log(niceRadio.htmlFor);
}
sliderWrapper.appendChild(radioWrapper);
.niceRadio {
position: relative;
width: 20px;
height: 20px;
cursor: pointer;
border-radius: 50%;
border: 5px solid orange;
}
.niceRadio:hover {
border-color: lightblue;
}
<div id="sliderWrapper">
</div>
The htmlFor is used to bind a label to a specific form element. However, it uses the id of that form element (not the name).
Source MDN:
The HTMLLabelElement.htmlFor property reflects the value of the for
content property. That means that this script-accessible property is
used to set and read the value of the content property for, which is
the ID of the label's associated control element.
Also, in your fiddle, you misspelled label.
Updated fiddle: https://jsfiddle.net/h09mm827/2/
A function for creating style constructed as follows
function createStyle(css) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
var textNode = document.createTextNode(css);
style.append(textNode);
}
head.append(style);
}
inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab
createStyle(`
.tab button {
background: inherit;
float: left;
outline: none;
border: none;
padding: 8px 6px;
width: 60px;
cursor: pointer;
}
`);
and a HTML element using the style
var div = document.createElement("div");
div.className = "tab";
parent.append(div);
is also created. So it all works.
After that I need to modify the style with class name tab, where following code
var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];
is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.
The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].
Proposed solution
Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function
// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
var N = document.styleSheets.length;
var styles = document.styleSheets;
for(var i = 0; i < N; i++)
{
if(styles[i].rules[0].selectorText == style)
styles[i].rules[0].style[attr] = value;
}
}
which is called
changeStyleAttribute(".tab", "width", "299px");
and works. I hope there is another better and simpler solution.
You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);
Refer to this link: How to change/remove CSS classes definitions at runtime?.
Hope this helps.
How to write css code in javascript? (Uncaught TypeError: Cannot set property "height" of undefined)
javascript
document.getElementById("slideshow").getElementsByClassName("arrow").style.height = "86px";
css
#slideshow .arrow{
height:86px;
width:60px;
position:absolute;
background:url('arrows.png') no-repeat;
top:50%;
margin-top: -43px;
cursor: pointer;
z-index: 5000;
}
The key here is the pluralisation of getElementsByClassName - elements. This method returns an array-like object of elements, not just one element.
To apply the style to each, you need to loop through this array-like object and add the styles to each individual element returned:
var elems = document.getElementById("slideshow").getElementsByClassName("arrow");
for (var i = 0; i < elems.length; i++)
elems[i].style.height = "86px";
document.getElementsByClassName returns an array.
You have to loop through it, or if you know the index, do this:
document.getElementById("slideshow").getElementsByClassName("arrow")[0].style.height = "86px";
or
document.getElementById("slideshow").getElementsByClassName("arrow")[i].style.height = "86px";
i being your loop variable.
A bit of theory:
Changing HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
Here is the example:
// JavaScript demonstration
var changeBg = function (event) {
console.log("method called");
var me = event.target
, square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(clearDemo, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 20em;
height: 20em;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
JavaScript-Based Style Sheets - http://www.w3.org/Submission/1996/1/WD-jsss-960822
Mozzila's Web Developer guide - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/JavaScript
While I've started with explanation and theory #James Donnelly already provided my answer, which I've wanted to use:
var elements = document.getElementById("slideshow").getElementsByClassName("arrow");
for (var i = 0; i < elems.length; i++) {
elems[i].style.height = "86px";
.
As someone already pointed out,
document.getElementsByClassName returns an array (N Objects)
while
document.getElementById returns an element (ONE object)
This is because N elements can have the same class but only ONE item can have a particular ID.
Since you can't edit more items' attribute at once, you must cycle them and edit the attribute of each one by one
document.getElementById("slideshow").getElementsByClassName("arrow")[0].style.height = "86px";
document.getElementById("slideshow").getElementsByClassName("arrow")[1].style.height = "86px";
document.getElementById("slideshow").getElementsByClassName("arrow")[2].style.height = "86px";
.....
document.getElementById("slideshow").getElementsByClassName("arrow")[N].style.height = "86px";
This can be achieved by using a for cycle or a each one.
So I have a div (with the id of "thecolor2") that I want to append to an unordered list, but before I append it, I want to set its background color to a variable which has the value of a hex code. However, for some reason, it doesn't take in the color.
Here is the CSS:
#thecolor2{
height: 50px;
width: 50px;
border-radius: 100px;
border: 1px solid yellow;
position: relative;
bottom: 635px;
}
Her is the HTML:
<ul id = "allposts"></ul>
And here is the JS:
var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
$("#thecolor2").css("background-color", color);
thestream.appendChild(oneofpost);
thestream.appendChild(thecolor2);
You cant use a jQuery ID selector to match a node which hasn't been added to the document tree. You can simply use plain DOM to set its inline CSS style like this:
thecolor2.style.backgroundColor = color
As described by Carlo in another answer, you cannot use the jQuery selector to select elements that haven't been added. You can however, turn a created DOM element into a jQuery object by doing:
var thecolor2 = $(document.createElement('div'));
However, if you're going to be using jQuery then I suggest writing everything in jQuery, otherwise stick with using pure JavaScript for everything.
jQuery
var thestream = $('#allposts');
var oneofpost = $('<li></li>');
var thecolor2 = $('<div></div>');
thecolor2.prop('id', "thecolor2")
.css({
backgroundColor: color
}).appendTo(oneofpost);
thestream.append(oneofpost);
See jsFiddle
JavaScript
var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
thecolor2.style.backgroundColor = color;
oneofpost.appendChild(thecolor2);
thestream.appendChild(oneofpost);
See jsFiddle
Also I'm assuming you're trying to append a list item to the ul, so I corrected the code you had there with appendChild.
I have below CSS and and has one JavaScript file where I am getting Width property value say 50px.
I want to put that JavaScript Width property Value to below CSS
.carpe_slider_slitss {
BORDER-LEFT: #5256BB 1px solid; WIDTH: 100px; COLOR: #5256BB;
}
so the above CSS should look likes
.carpe_slider_slitss {
BORDER-LEFT: #5256BB 1px solid; WIDTH: 50px; COLOR: #5256BB;
}
So, how can I pass that JavaScript value to Width property value of CSS.
Please help.
element.style.width = '50px';
Where element is a reference to the element.
You can not manipulate external file via javascript. If your class is located in an external css file then you can not change that.
What all developers do is changing classes that located in current html file or changing style attribute
if you want to change the css styleSheet rules for all elements, you can do that with simple javascript:
function findCssRule(cssSelectorName)
{
var stylesheets = document.styleSheets;
for(var i = 0, ii = stylesheets.length;i<ii;i++)
{
for(var j = 0, jj = stylesheets[i].rules.length;j<jj;j++)
{
if(stylesheets[i].rules[j].selectorText == cssSelectorName)
{
return stylesheets[i].rules[j];
}
}
}
return null;
}
//set the width to 80px for '.carpe_slider_slitss' css rule
var cssRule = findCssRule('.carpe_slider_slitss');
if(cssRule!=null)
cssRule.style.width = '80px';
this is a way to do it
//ether create a new style sheet
var style = document.createElement ("style");
document.getElementByTagName('head')[0].appendChild(style);
//or find a document you want to edit
//ether local
var style = document.getElementByTagName('style')[0];
//or imported
var style = document.getElementByTagName('style')[0];
style = style.sheet ? style.sheet : style.styleSheet;
if(style.insertRule){
//insertRule('your css code',new rule index);
style.insertRule('carpe_slider_slitss{ width: 50px; }', style.cssRules.length); //You can use 0 to insert your rule at the start of the style
}else{ //this is the ie < 9 way
style.addRule('carpe_slider_slitss', 'width: 50px', style.cssRules.length);
}