I am new to JS. I want to change css for all elements selected by className. I did some search and I found the solution below. But, it will only affect the first element. I am wondering if there is a easy to to change the css for all selected elements.
document.getElementsByClassName('ads')[0].style.display = 'none';
document.getElementsByClassName('class')[x]
may be x can be 0,1,2,... depends on elements with that class if there two div with ads
class you will count from 0 as the first div with that class because it returns in array
or you can use tag name while you are selecting
document.getElementsByTagName('div')[x]
this also returns in array because in html suppose to be many similar tags means that you have to index to them
document.getElementById('id')
this is selecting by using the tag's id and an id there a tag with an id should be the unique thats why this doesn't return in array means that you don't need to index on it
document.querySelectorAll('p .class')[x]
with selector you do it like you do in css but it returns in array to and also you can apply the pseudo classes and elements
document.querySelector('p .class')
this used like the above one but it didn't return in array so you don't have to index on it
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
document.querySelectorAll('.ads').forEach(ele => {ele.style.display = 'none'});
This should do it. The querySelectorAll-method returns you a Nodelist from a given css-selector. The first line checks if there is already a forEach method and if not it will inherit it from the Array Object.
You can also read about the from method of the Array object this could be a more cleaner version.
You need to use loop, please check snippet
NOTE: I added '.hide' class and set background color just to display result. you just add display:none in CSS
window.onload = function() {
var ads = document.getElementsByClassName("ads"),
len = ads !== null ? ads.length : 0,
i = 0;
for(i; i < len; i++) {
ads[i].className += " hide";
}
}
.hide {
background: skyblue;
}
<div class="ads">1</div>
<div class="ads">2</div>
Simple with jQuery method :
$('.ads:first').hide();
$('.ads:first').css("display":"none");
To using jQuery, you have to add jQuery plugin inside <body> tag before jQuery function call :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Related
Assuming that I have the following HTML:
<body>
<section role="main">
</section>
</body>
1) Can I do this?
var section = document.getElementsByTagName("section");
2) Can I do this?
var section = document.querySelector("section[role=main]");
3) And finally, how can I append childs to this element? appendChild() doesn't work.
var p = document.createElement("p").innerText("A paragraph.");
section.appendChild(p);
You can use either 1 or 2,
Using getElementsByTagName -
check out the fiddle - http://jsfiddle.net/2jzho6hh/3/
this one returns an array of all elements with tag name section, so to access the first section element you have to use the 0 index on the array. For the second element use 1 index on the array and so on..
Using querySelector,
check the fiddle - http://jsfiddle.net/2jzho6hh/2/
querySelector returns first element matching the selector you have specified as in this case section[role=main] which means select the first sectionelement with attribute role and its value being main
There is also one other method querySelectorAll which is, you may think, a union of above two methods. It selects elements on the basis of CSS selector syntax just like querySelector does and it returns an array of all elements matching the selector just like the getElementsByTagName
Correct code is
var p = document.createElement("p");
p.innerHTML="A paragraph";
section.appendChild(p);
don't add innerHTML at the time of declaring p.If you do so p will not return child node.Declare p as a node and then add innerhtml to it.
$("selector").attr("id","idname");
Is it possible to use above for setting ID or Class of an element.
hm i feel like i've said it thousands of times. The jQuery class selector returns an array of all HTML elements with that class. So, if you want to get data form those elements you need to loop over the array or access it directly.
$('.gg1').first().attr("id"); //returns the id of the first element with class gg1
$('.gg1')[1].attr("id"); //returns the id of the second element with class gg1
for(var i = 0; i < $('.gg1').legth; i++= {
console.log($('.gg1')[i]); } //loops over the cormplete HTML Collection
http://api.jquery.com/attr/
http://www.google.com
I have a long list of image elements, each with it's own ID. I've already set it up so that when you click on one image, it will toggle a class "foo".
What I'd like to do is set it up so that when you click on another image, the first image's class "foo" will be removed. I'd like to do this with pure javascript if possible. Thanks.
Here's a fiddle: http://jsfiddle.net/q3aRC/
function clicked($id) {
document.getElementById($id).classList.toggle('foo');
}
I'd suggest, given that you're already using the classList api:
function clicked($id) {
// get all the elements with the class-name of 'foo':
var others = document.querySelectorAll('.foo');
// if there *are* any elements with that class-name:
if (others.length){
// iterate through that collection, removing the class-name:
for (var i = 0, len = others.length; i < len; i++){
others[i].classList.remove('foo');
}
}
/* add the class-name back (if it already had the class-name
we removed it in the previous section): */
document.getElementById($id).classList.add('foo');
}
JS Fiddle demo.
References:
document.querySelectorAll().
element.classList.
I would add a common class to all images and remove the foo class from all of them. Then I would add the class to the specific image
function clicked(id){
var images = document.getElementsByClassName('images');
for (var i = 0; i < images.length; ++i) {
images[i].classList.remove('foo');
}
document.getElementById(id).classList.add('foo');
}
Since you are already using classList I assume you're only catering to browsers new enough for addEventListener(), so I'd suggest removing all of the onclick attributes and doing something like this:
document.addEventListener('click',function(e){
if (e.target.tagName === "IMG") {
var imgs = document.getElementsByTagName('IMG');
for (var i = 0; i < imgs.length; i++)
if (imgs[i] != e.target)
imgs[i].classList.remove('foo');
e.target.classList.toggle('foo');
}
}, false);
Demo: http://jsfiddle.net/q3aRC/3/
That is, bind a single click handler to the document (or you could bind to a parent element of the images if they share a common parent), and then on click test if the clicked item is one of the elements you care about (i.e., an img) and go from there... The JS ends up about the same length, but the html ends up shorter and neater. You could actually remove the id attribute too if you weren't using it for anything other than your original clicked() function.
I used getElementsByTagName() just to show you yet another way of doing it, but getElementsByClassName() or querySelectorAll() (as in the other answers) are probably better options. But that's an easy switch to make.
I was working on an issue in which I was looping through same controls placed on a single page and assigning a z-index to them.
I want to get a collection of all the elements which currently have the z index defined either directly in html or using css, and then iterate over them top to bottom and assign their z-index using JQuery.
What would the selector for this look like, and how performant would it be?
There is no specific selector to achieve this, so you would need to use filter() like this:
var zIndex = 5;
var $zElements = $('.selector').filter(function() {
return $(this).css('z-index') == zIndex;
});
$zElements.each(function() {
// loop through the elements with a matching z-index
});
I am trying to write a method that grabs all the elements of a certain classname for browsers that don't have the 'getElementsByClassName' method. This works perfectly for elements that are generated server-side, however the page has the ability to add elements dynamically for some reason 'window.document.all' does not get these dynamic elements. Any ideas? Method below.
function getClassName(class) {
var i, neededStuff = [], elements = document.getElementsByTagName('*');
for (i = 0; i < elements.length; i++) {
if (elements[i].className == class) {
neededStuff[neededStuff.length] = elements[i];
}
}
return neededStuff;
}
class is a reserved keyword in IE. Don't use it literally. Change class to something like theClass.
Also, try document.getElementsByTagName('*') instead of document.all if changing class doesn't do it.
EDIT:
http://work.arounds.org/sandbox/72
Works perfectly for me in IE6 ^
Let me try dynamically adding...
EDIT #2: works fine..
http://work.arounds.org/sandbox/72
Use jQuery :)
http://jquery.com/
$('.ClassName')
will return your elements :)
then you can change it's value, add classes very easily!
Some great tutorials here
http://docs.jquery.com/Tutorials