Master element attribute? (or technique) - javascript

Is there any way you can set an element to be a master and have all other elements on a page appear and behave in exactly the same, same style, same code, same attributes, same values?
<input id="btnBack" name="btnBack" type="button" value="Back" disabled="disabled" style="margin-right: 10px" />
$('#btnBack').click(...do stuff);
<input master="btnBack" />
Or failing this is there any technique to concisely achieve the same result?
I'm half expecting there to be a Javascript library out there that copies all the attributes.

Same style = css
Same attributes, values, etc = JS
See this fiddle for an example to get you started or this code snippet...
The CSS
input {
width: 200px;
background-color: yellow;
}
The JS
var value = 'myval';
var disabled = 'disabled';
var myElements = document.getElementsByTagName('input');
for(var i = 0; i < myElements.length; i++){
myElements[i].value = value;
myElements[i].disabled = disabled;
}

Yes with CSS classes. Create a master class and then use the class="master" on all your elements.
However I think you'll find you don't really want to do this once you get into it. But it will be easy to change the class on the elements you want to change so it won't hurt you to get started this way.
You can read about CSS here: http://www.w3schools.com/css/ though there are better resources w3schools covers a lot of ground.
If you're interested in building a consistent feel to a site and don't mind using jquery (which I love!) then you should checkout the jquery UI themeroller:
http://jqueryui.com/themeroller/

I don't know if this is what you're referring to, but best bet is use a class on all the elements you want to style and behave the same.
E.g.
File: index.html
Awesome Link
<button class="master-class">Awesome Button</a>
File: style.css
.master-class {
color: black;
background: white;
more of your styles...
}
File: scripts.js
$(function() {
$(".master-class").click(function() {
alert("This is from one of the many elements with the class 'master-class'");
});
});
Team Treehouse is a great place to really learn all about everything web. I've been using them for a while even though I knew most of the stuff on there, but I always pick up a few new things. http://teamtreehouse.com/
W3Schools ( http://www.w3schools.com ) is also great. It's where I learnt a lot of stuff in the beginning.
There is also a large amount of podcasts and vodcasts out there to teach you too, just search iTunes for web design.

Related

Why ican't it find the display property? (more below)

I added a event listener to a button, which would show the css of the #popUpForm, however on the console it logs nothing.
markup:
<input id = "addItem" type = button value = "+">
<div id = "popUpForm">
/* lot of divs*/
</div>
script:
const addBtn = document.querySelector('#addItem')
addBtn.addEventListener('click', function(){
console.log(document.querySelector('#popUpForm').style.display)
})
css:
#popUpForm{
width: 350px;
height: 500px;
display:none; <-- looking for this
}
I'm using webpack, is it possible, that somehow it messes up my code? Any help appreciated!
element.stylerefers to inline styles only.
To check for currently applied styles regardless of the source, use
window.getComputedStyle(document.querySelector('#popUpForm')).display
instead. Beware that this a very expensive call performance-wise, so only ever use it when no better solution is available.
That being said, I'd suggest working with the API for the job, which is the hidden API, which would simplify the check for visibility to
document.querySelector('#popUpForm').hidden
Especially, this makes it very easy to toggle visibility:
document.querySelector('#popUpForm').hidden = !document.querySelector('#popUpForm').hidden

How to Style H1 Tag with Javascript in Squarespace Template

Our Squarespace site has a catalogue containing products from multiple brands. I'm trying to ensure the brand name stands out by making it bold but given the way Squarespace works, I need to add Javascript into the page to manipulate the html.
Using Chrome Dev tools on the product titles, I can see the html class is called '.ProductList h1.ProductList-title'.
I've tried implementing the below, but haven't had much luck so far - am I even on the right track?
function changeBrandName()
{
var prodList = document.getElementsByClassName(".ProductList h1.ProductList-title");
for (i = 0, len = prodList.length; i < len; i++)
{
prodList[i].style.color = 'red';
}
}
window.onload = changeBrandName();
Squarespace class structure:
<section class="ProductList-overlay">
<div class="ProductList-meta">
<h1 class="ProductList-title">Vifa - Pebble Grey Oslo Loudspeaker</h1><style></style>
<div class="product-price">
<span class="sqs-money-native">0.00</span>
</div>
</div>
</section>
(this is one of the pages we're displaying products https://www.manilva.co/catalogue-electronics/).
Take a look: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
when using getElementsByClassName, you do not need to pass in CSS selectors, like you have done. You just need to pass in the actual name of the classes. Or, use the querySelectorAll with the parameters you had originally. querySelector, as daksh mentioned, will only return the first element that matches
function changeBrandName()
{
var prodList = document.querySelectorAll(".ProductList h1.ProductList-title"); //returns static NodeList of all elements in DOM that match the provided classes
for (i = 0; i < prodList.length; i++)
{
prodList[i].style.color = 'red';
prodList[i].style.fontWeight = 'bold'; //W is capital
}
}
You've indicated that you must use Javascript. However, Squarespace supports custom CSS (currently under Design > Custom CSS while editing your site). Having read through the question, I see no details that preclude the use of CSS (though perhaps such details were simply left out).
If using CSS is an option, inserting the following via Custom CSS is all that is needed:
.ProductList h1.ProductList-title {
color: red;
font-weight: bold;
}
If for some reason you want to target only a specific collection, you can add further specificity to the selector via the collection ID, used as the id attribute on the body element:
#collection-5c1cf955898583ce09da99a0 .ProductList h1.ProductList-title {
color: red;
font-weight: bold;
}
If you choose to go the CSS route, be sure you evaluate and remove any previous code you've added related to this particular need.

Changing paragraph style using childNodes in JavaScript

I'm new at JavaScript. I have an html document and I want to change to fontsize of paragraphs that are inside a div but I'm having a problem. I got this error in the console:
Uncaught TypeError: Cannot set property 'fontSize' of undefined codigo.js:5
This is my html:
<!DOCTYPE html>
<html leng="es">
<head>
<meta charset="UTF-8">
<title>Mi ejercicio DHTML</title>
<link rel="stylesheet" type="text/css" href="css/estilos.css">
<script type="text/javascript" src="js/codigo.js" ></script>
</head>
<body>
<div id="parrafos">
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
</div>
</body>
</html>
This is my js:
window.addEventListener('load', inicio);
function inicio(){
var parrafos = document.getElementById('parrafos');
parrafos.childNodes[0].style.fontSize='10px';
}
What I want is by using the childNodes on the div called parrafos change the style of every paragraph by accessing its index parrafos.childNodes[2].style.... etc etc
[EDIT]
I ended with this code:
window.addEventListener('load', inicio);
function inicio(){
var parrafos = document.getElementById('parrafos');
parrafos.childNodes[1].style.fontSize='1.5em';
parrafos.childNodes[3].style.fontSize='1.3em';
parrafos.childNodes[5].style.fontSize='.5em';
parrafos.childNodes[7].style.fontSize='1em';
parrafos.childNodes[9].style.fontSize='.2em';
}
and I found that because of space en html documents it doesn't follows a consecutive order it seems weird because I thought it should go consecutive.
Try this:
window.addEventListener('load', inicio);
function inicio(){
var parrafos = document.getElementById('parrafos');
for (var i=0; i<parrafos.children.length; i++) {
parrafos.children[i].style.fontSize = '10px';
}
}
In your example you should set the fontSize to '10pt' instead of '10px' (or '1em') see: http://jsfiddle.net/K9Uhn
var parrafos = document.getElementById('parrafos');
parrafos.childNodes[1].style.fontSize='10pt';
Also, You should also look into using jQuery for this. It would save you a ton of headaches as it handles the element iteration and dom issues itself. For example, the jQuery code to change all the font sizes for the above example would be
$("#parrafos").css("font-size", "10pt");
No need to do the for loop yourself, jQuery handles all this. And, it's compatible with all browsers (something you will find is a huge plus): www.jquery.com
Tweaking the styles like this on a per-element basis is not a good idea. Stylesheets and element clases are your friend!
Please think about the next guy who picks up your code. They need to change the font size. They look in the stylesheet, where you would expect to find that value, and it's not there. After a few hours they find it in the JavaScript, where you wouldn't expect it. Then they get off work, drink heavily and botch about your code to their friends because of how hard you just made their day.
Maintanability is the thing that minimizes how often this scenario occurs.
So instead, how about you give your body class a tag, and have some styles that change font sizes based on that?
/* Stylesheet */
p {
font-size: 16px
}
body.small p {
font-size: 10px
}
Now your JS function that takes the action simply becomes this:
// Javascript
function inicio(){
document.body.className = 'small';
}
Which is far easier to manage.
See it work here: http://jsfiddle.net/s6BAf/
In general, dont use inline styles in your HTML, or set CSS values directly in your javascript if you can avoid it. Instead, manipulate the classes of elements on your page, and let your stylesheet do what it does: style your content.

Search for div classes with regex

Sounds simple, huh. Lot's of answers i found but all use jQuery or ProtoType. I want plain JavaScript. It shouldn't be that hard, but JavaScript is not my thing; no central documentation means searching for ages and not finding what i want.
Consider the following HTML code snippet:
<div class="central_0"> .. </div>
<div class="central_1"> .. </div>
<div class="central_2"> .. </div>
Now I want to use JavaScript to do things with those DIVs.
function processDivElements()
{
// search for relevant DIV classes
var divArray = document.getElementsByClass.regex('/^central_.*$/');
// do stuff with the DIV elements found
foreach (divArray as divElement)
{
divElement.style.background = '#f00';
};
}
Can anyone help me translate this to proper plain JavaScript? I use classes, not IDs. I prefer using a regular expression.
The jQuery solution is really nice:
var $divs = $('div[class^="central_"]');
If you only want to support newer browsers, you can use document.querySelectorAll() to do essentially the same thing:
var divs = document.querySelectorAll('div[class^="central_"]');
If you want to support older browsers, the code gets horrible:
var all_divs = document.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < all_divs.length; i++) {
var div = all_divs[i];
if (div.className.match(/^central_\d+$/) {
divs.push(div);
}
}
Also:
I use classes, not IDs. I prefer using a regular expression.
Your classes are unique and are really functioning like IDs, which isn't really the intended use of classes. Structure your HTML like this instead:
<div id="central_0" class="central">...</div>
<div id="central_1" class="central">...</div>
<div id="central_2" class="central">...</div>
Now, the JavaScript becomes simpler:
var $divs = $('.central'); // jQuery
var divs = document.querySelectorAll('.central'); // Newer browsers
var divs = document.getElementsByClassName('central'); // Older browsers
As the others have mentioned you can't directly support a regex select on the getElementsByClassName method call.
But I will point out these other issues with your code, since you are new to javascript.
Using classes is fine, but your making more work for yourself by writing up your html like that.
Instead of the central_0....central_2 if they are all basically operating on the same css rules, you should write them like this central zero....central two then your central class can have identical rules, while you can assign any differences to the # classes. This way your also adhering to the DRY principle.
Also you should really consider sticking to the best practices for the language. If your not assigning css rules to your elements with those classes then you should be using id's, plus it makes your life much easier.
There is no way to get the matched elements by regex directly, the only thing you could do is to get all the elements by something (like: TagName, Name, etc..) and then filter the elements by regex.
With your html sample, you could only get all the element by TagName, and use regex to check the className by regex.
One quicker way to do so is to create a simple <style> as follows:
<style>
div[class^="central_"] {
background-color: #f00;
}
</style>
Therefore, as you look for plain javascript, useless to say that you can add <style> tags at will, by using javascript. A whole HTML example as follows:
<html>
<head>
</head>
<body>
<div class= "central_1">
central 1
</div>
<script>
var css = "<style>div[class^=\"central_\"] {background-color: #f00;}</style>";
var list = document.querySelector("head"); list.innerHTML += css;
</script>
</body>
</html>

Need Javascript syntax to reference a CSS class instead of HTML element

I searched online for the correct syntax to reference a CSS class, instead of an HTML element, but was unable to find anything helpful.
I would like to modify the code below to reference any DIV of class buy_content "div.buy_content" instead of the body element.
Small Text
Medium Text
Large Text
There is no "JavaScript syntax" for what you're asking for. Newer browsers support an API called "getElementsByClassName", so you could do this:
function setSize(sz) {
var elements = document.getElementsByClassName('buy_content');
for (var i = 0; i < elements.length; ++i) {
if (elements[i].tagName === 'DIV')
elements[i].style.fontSize = sz;
}
}
<a href='#' onclick='setSize("1em"); set_cookie(...);'>Small</a>
You can find a "patch" for "getElementsByClassName" support here.
<a href="#" class="clickie size-1" >Small text </a>
<a href="#" class="clickie size-2" >Medium text </a>
<a href="#" class="clickie size-3" >Large text </a>
You should change the markup not to rely on inline javascript.
// bind the event handler to all <a> tags
var as = document.getElementsByTagNames("a");
for (var i = 0, ii = as.length; i < ii; i++) {
as[i].onclick = setText;
}
function setText(ev) {
// get the em size from the class
var size = /[.]*text-([\d][.]*)/.exec(ev.target.className)[1]
var divs = document.querySelectorAll("div.buy_content");
// set the style on all divs.
for (var i = 0, ii = divs.length; i < ii; i++) {
divs[i].style.fontSize = size + "em";
}
}
There are issues with browser support (mainly IE7 and lower) so you need some more boilerplate to make it work.
You can't really do this (easily/readably/cleanly) with inline and stock JavaScript because the JavaScript DOM API doesn't provide a way to reference a CSS class since this isn't part of the DOM. You would have to populate an array or list with HTML elements that have that class applied to them and then iterate over the collection.
JQuery provides selectors and iterators to make this very simple, but if you can't use libraries then doing this inline isn't a good idea. Put it in a function in a script block or an external .js file.
EDIT:
A few people pointed out querySelectorAll, which will select by class but from what I have read isn't completely cross platform (doesn't work on IE below IE 8).
Further, to clarify on my original post, when I said that the DOM API doesn't allow you to access an element by class, what I meant was that it couldn't be done with DOM traversal. querySelectAll or the JQuery selectors perform DOM traversal with functions that inspect elements and their properties, retrieve the objects, and populate collections. Even getElementById performs attribute inspection. I suppose, in retrospect, it's a moot point, but since he wasn't using selectors or attribute queries in his original code I thought that he was asking if there was JS syntax that was as simple as what he was currently using. That's why I mentioned functions. In my head, even something like getElementById is a function since, well, it is a function.
I believe what you are looking for is insertRule (this is exactly what you asked for... kinda):
document.styleSheets[document.styleSheets.length-1].insertRule('div.buy_content {font-size: 1em}',document.styleSheets[document.styleSheets.length-1].length)
document.styleSheets[document.styleSheets.length-1] is your last stylesheet.
the new rule will go at index document.styleSheets[document.styleSheets.length].length
http://www.quirksmode.org/dom/w3c_css.html#t22
also... deleteRule:
http://www.quirksmode.org/dom/w3c_css.html#t21
BUT, a better way to go would be to getElementsByClassName, loop through em, check their nodeName for "DIV", then apply the styles the old fashioned way.
Leverage CSS to do the selection work for you:
body.smalltext .buy_content { font-size: 1em; }
body.mediumtext .buy_content { font-size: 2em; }
body.largetext .buy_content { font-size: 3em; }
...
<input type="button" value="Small text" id="smalltext"/>
<input type="button" value="Medium text" id="mediumtext"/>
<input type="button" value="Large text" id="largetext"/>
...
document.getElementById('smalltext').onclick= function() {
document.body.className= 'smalltext';
};
document.getElementById('mediumtext').onclick= function() {
document.body.className= 'mediumtext';
};
document.getElementById('largetext').onclick= function() {
document.body.className= 'largetext';
};
My first suggestion to answer your exact question:
If your project is bigger in scope than just this one thing:
Download jQuery
Use code:
$('div.buy_content')
Which returns a jQuery array object of all the divs which you can further manipulate.
My second suggestion based on thinking more deeply about what you're trying to do:
Either completely replace the stylesheet in script or modify the existing stylesheet to change the style. Don't loop through all the DIVs in the document and change their style assignment, instead change the meaning of their already-assigned style.

Categories

Resources