Set CSS properties on multiple HTML elements - javascript

I have this part of a function that sets css properties on two buttons (update, save). I'm trying to minimize the lines of code and i'm looking for a more efficient way of setting css properties on multiple HTML elements rather than writing getElementById for every element. Is querySelectorAll suitable for use in this context?
//Chris
var css = {"backgroundColor": "red","textDecoration": "line-through"};
for (var prop in css) {
document.getElementById("update").style[prop] = css[prop];
document.getElementById("save").style[prop] = css[prop];
}

Yes, querySelectorAll could be used in this context. Be aware that it isn't supported in IE8 or earlier. Check out the MSN docs for some quirks.
In addition, be aware that querySelectorAll returns an array like object (a non live NodeList) so you'll have to modify your code to work with such a structure:
var css = {"backgroundColor": "red","textDecoration": "line-through"};
var matched = document.querySelectorAll("#update, #save");
matched.forEach(function (c){
c.style.backgroundColor css.backgroundColor;
c.style.textDecoration = css.textDecoration;
});

I'd suggest the following method
var css = {"backgroundColor": "red","textDecoration": "line-through"};
var elements = document.querySelectorAll('#update, #save');
for (var prop in css) {
elements.forEach(function (element) {
element.style[prop] = css[prop];
});
}
here the querySelectorAll is used with multiple selectors

Using document.querySelectorAll you could do it this way.
/*declare a css class*/
.button-css{"backgroundColor": "red","textDecoration": "line-through"};
/*in javascript you can do the following*/
var buttons=document.querySelectorAll(".buttons");
buttons.forEach(function(button){
button.classList.add('button-css');
})

Related

Onclick doesn't work in userscript [duplicate]

I am trying to run a function onclick of any button with class="stopMusic". I'm getting an error in Firebug
document.getElementByClass is not a function
Here is my code:
var stopMusicExt = document.getElementByClass("stopButton");
stopButton.onclick = function() {
var ta = document.getElementByClass("stopButton");
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
You probably meant document.getElementsByClassName() (and then grabbing the first item off the resulting node list):
var stopMusicExt = document.getElementsByClassName("stopButton")[0];
stopButton.onclick = function() {
var ta = document.getElementsByClassName("stopButton")[0];
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
You may still get the error
document.getElementsByClassName is not a function
in older browsers, though, in which case you can provide a fallback implementation if you need to support those older browsers.
Before jumping into any further error checking please first check whether its
document.getElementsByClassName() itself.
double check its getElements and not getElement
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById(), then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
It should be getElementsByClassName, and not getElementByClass. See this - https://developer.mozilla.org/en/DOM/document.getElementsByClassName.
Note that some browsers/versions may not support this.
My solutions is:
Change:
document.getElementsByClassName('.className')
To:
document.querySelector('.className')
you spelt it wrongly, it should be " getElementsByClassName ",
var objs = document.getElementsByClassName("stopButton");
var stopMusicExt = objs[0]; //retrieve the first node in the stack
//your remaining function goes down here..
document['player'].stopMusicExt(ta.value);
ta.value = "";
document.getElementsByClassName - returns a stack of nodes with more than one item, since CLASS attributes are used to assign to multiple objects...
it should be getElementsByClassName NOT getElementByClassName ==> you missed "s" in Elements
const collectionItems = document.getElementsByClassName('.item');
document.querySelectorAll works pretty well and allows you to further narrow down your selection.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
document.getElementByClass is not a function
Yes, it is not a function nor method because it should be document.getElementsByClassName
enter code here
var stopMusicExt = document.getElementByClass("stopButton").value;
stopButton.onclick = function() {
var ta = document.getElementByClass("stopButton");
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
// .value will hold all data from class stopButton
The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)
function stop(ta) {
console.log(ta.value) // document['player'].stopMusicExt(ta.value);
ta.value='';
}
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
If you wrote this "getElementByClassName" then you will encounter with this error "document.getElementByClass is not a function" so to overcome that error just write "getElementsByClassName". Because it should be Elements not Element.

Equivalent of getElementById for Classes in Javascript

I'm currently making a game, and I'm trying to change the CSS values of a whole class of objects. For a single ID, I would use, document.getElementById("idHere"), but I need something like document.getElementByClass("classHere"). Thanks!
There is simply document.getElementsByClassName("myClass"), which returns an array of all the elements with that HTML class.
If you're using jQuery, you can do it with $(".myClass"), which will return a collection of all of the elements with that class.
There exists getElementsByClassName; see document.getElementsByClassName on MDN.
If you can use JQuery I suggest $('.classHere').
Two ways to do it:
document.getElementsByClassName("theClassName");
document.querySelectorAll(".theClassName");
These methods won't work on older browsers (like IE7 or IE8). In this case you'll have to iterate through elements to check the class name, or rely on a library like jQuery.
If you can't or don't want to use jQuery, do the following:
function changeClassName(className, newClassName) {
var elements = document.getElementsByClassName(className);
for (var i = 0; i < elements; ++i) {
var item = elements[i];
item.className = newClassName;
}
}
If you decide to use jQuery:
function changeClassName(className, newClassName) {
$('.'+className).toggleClass(newClassName);
}
If you need to change CSS values according to class name you can just use:
document.getElementsByClassName("classname");
this will return you an array of all elements in whole document that have class which you search.
This will allow you to write a loop to change CSS for all of returned elements.

how to style a-tags nested in div with id using pure javascript

I'm used to JQuery but not to pure Javascript.
I have this:
document.getElementById("div-id a").style.javascript_property = "color: red;";
OF COURSE it doesn't work.
What i want is that all a-tags in one specific div with an id='div-id' to become red.
in jquery i would write:
$('#div-id a').css('color', 'red');
But i need it in pure js.
Use:
var div = document.getElementById("div-id");
var list = div.getElementsByTagName("a");
for (var i = 0; i < list.length; i++) {
list[i].style.color = "red";
}
The getElementById method takes a string representing an id, not a selector. The clue is in the name. The querySelectorAll method takes a string representing a selector, but it returns a nodeList, so you would have to loop over it like an array.
The property name which you have called javascript_property needs to match the CSS property name (with hyphenated-words turned into camelCase) (so it should be "color").
The value you give it needs to match the CSS properties value, not the entire rule (so "red").
None of this, however, is pure JavaScript. It is DOM (except for querySelectorAll which is from the Selectors API).

How to make Javascript more specific?

I am new at JavaScript so I think my problem may be simple.
This works:
var convId = document.getElementById("wrapper");
convId.setAttribute("align","right");
But when I try to make it more specific:
var convId = document.getElementById("wrapper");
var convIdDl = convId.getElementsByTagName("dl");
convIdDl.setAttribute("align","right");
my definition list doesn't align to the right.
I have checked the HTML and CSS and everything is correct, but that shouldn't even matter
JavaScript overwrites them both.
The getElementsByTagName method returns a collection (to be more specific, a NodeList). You need to specify which element of that collection you want to use (just like you would when accessing an element in an array). Here I'm assuming you want the first:
convIdDl[0].setAttribute("align", "right");
As noted in the comments, you should definitely not be using the align attribute. CSS should be used in all cases.
The getElementsByTagName() function returns a collection of DOM elements, so you'll probably want to iterate through that and set the attribute on each element individually.
for(var i = 0; i < convIdDl.length; i++) {
convIdDl[i].setAttribute("align", "right");
}

Remove element created by JavaScript on load

How can I remove elements which are created by JavaScript, I tried using CSS by setting display:none; but that doesn't seem to solve my problem, also I can't remove them since I don't have them in HTML, any other ways? Thank you
UPDATE:
Can't use any JavaScript such as jQuery, MooTools, ExtJS etc, and actual elements I want to remove are divs, with a specified class so I can't use getElementById.
I found this script on Google, but it doesn't seem to work but this is what I need:
HERE
This is fairly simple to do this using jQuery.
$("#myId").remove();
will remove
<div id="myId"></div>
Edit: You can also do it with "old school" javascript.
The function you're looking for is removeChild()
Example:
function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
You will want something like this to take advantage of browser support where you can:
if(document.getElementsByClassName){
// Safari 3+ and Firefox 3+
var itms = document.getElementsByClassName('your_class');
for(var i = 0; i<itms.length; i++){
var it = itms[i];
if(it.tagName == "DIV"){
it.parentNode.removeChild(it);
i = i - 1; //It actually gets removed from the array, so we need to drop our count
}
}
} else {
// All other browsers
var itms = document.getElementsByTagName('div');
for(var i = 0; i<itms.length; i++){
var it = itms[i];
// Test that className contains your class
if(/your_class/.test(it.className)) it.parentNode.removeChild(it);
}
}
JavaScript handles all memory mangement for you using garbage collection so once all references to an object cease to exist that object will be handled by the browsers specific implementation.
If you have the dom element itself:
if(node && node.parentNode){
// return a ref to the removed child
node.parentNode.removeChild(node);
}
Since you say you can't use Javascript, you're pretty stuck. Have you tried this CSS:
.classname {
display: none !important;
}
It's possible that the created elements have inline styles set on them, in which case normal CSS is overridden. I believe the !important will override inline styles.
Of course, the best solution is not to add the element in the first place... but I'm guessing you're in one of those (unfathomably common) scenarios where you can't change or get rid of the JS?
Not all browsers have a
document.getElementsByClassName
method, but for your purpose you can
fake it well enough- This method does
not work like the native
HTMLElement.getElementsByClassName- it
returns an array, not a live nodelist.
You can specify a parent element and a
tag name to speed it up.
function getElementsByClass(css, pa, tag){
pa= pa || document.body;
tag= tag || '*';
css= RegExp('\\b'+css+'\\b');
var A= [], elements, L, i= 0, tem;
elements= pa.getElementsByTagName(tag);
L= elements.length;
while(i<L){
tem= elements[i++];
if(css.test(tem.className)) A[A.length]= tem;
}
return A;
}
// test
var A= getElementsByClass('removeClass'), who;
while(A.length){
who= A.pop(); // remove from the end first, in case nested items also have the class
if(who.parentNode) who.parentNode.removeChild(who);
who= null;
}
If you have assigned event handlers to
the elements being removed, you should
remove the handlers before the
elements.
You will probably have to be more specific.
The general answer is 'with JavaScript'. As long as you have a way of navigating to the element through the DOM, you can then remove it from the DOM.
It's much easier if you can use a library like jQuery or prototype, but anything you can do with these you can do with JavaScript.
marcgg has assumed that you know the ID of the element: if you don't but can trace it in the DOM structure, you can do something like this (in prototype - don't know jQuery)
var css_selector = 'table#fred tr td span.mydata';
$$(css).invoke('remove');
If you can't use a JS library, you'll have to do the navigation through the DOM yourself, using Element.getElementsByTagName() a lot.
Now you've specified your question a bit: use Element.getElementsByTagName, and loop through them looking at their className property.
Use:
document.removeChild('id_of_element');

Categories

Resources