I have many div with the class publish_0 that I would like to change to publish_1 on click of a button.
Right now I use this but it only change one item.
How to I apply the setattribute to all item that have the publish_0.
document.querySelector('.publish_0').setAttribute("class", "publish_1");
You need to use a loop to iterate over all the elements and set their class attribute value individually:
var els = document.querySelectorAll('.publish_0');
for (var i=0; i < els.length; i++) {
els[i].setAttribute("class", "publish_1");
}
For when you can't use jQuery but want the convenience of something similar, you can do the following. Add the following code to the top of the file or somewhere else easily visible.
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
Now in your code you can do this:
document.querySelectorAll('body,main,article,[class*=content],[class*=center]')
.forEach((function(x){ x.setAttribute("style","width:1920px");}))
Or even nicer yet, if the browser supports ECMAScript2015 you can use arrow syntax:
document.querySelectorAll('[class*=content]')
.forEach( x=> x.setAttribute("style","width:1200px"))
You can put the statement all on one line if you'd like.
You can use this with jquery:
$(".publish_0").attr("class", "publish_1")
Alternatively, use getElementsByClassName and loop through the DOM elements returned.
Related
I want to know if there is a way to getElementByClassName("classname").innerHTML function or something to the equivalent of getElementById("ClassName").innerHTML.
You are missing an s in your function name. getElementsByTagName returns a collection of elements, of elements, which you need to iterate over:
var elements = document.getElementsByClassName("classname");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = 'foo';
}
IE8 and below don't support getElementsByClassName, so you'll have to find a polyfill or use querySelectorAll (IE8).
I suggest you to use JQuery, where you can use directly CSS selectors (like .yourclass) to find all elements of a given class:
$('.yourclass').doWhatYouWant();
If you prefer not to use JQuery, you can use plain Javascript:
document.getElementsByClassName('my-fancy-class')
But be careful with IE8 incompatibility issue.
As an alternative (slower but you can build more complex CSS selectors) you can use:
document.querySelector('.cssSelector')
Which will return one element responding to your CSS selector, or
document.querySelectorAll('.cssSelector')
Which will return multiple elements instead.
You can do this using jquery
$('.className').html();
http://api.jquery.com/html/
If tou use jQuery you can get it as you would in a CSS selector so:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
then...
$('.classname').each(function() {
// get html
$(this).html();
// set html
$(this).html('something');
});
Notice you have also convenient way to manage innerHTML.
http://jsfiddle.net/PhilFromHeck/KzSxT/
In this fiddle, you can see at line 38 in the Javascript that I've attempted to make a comparison that isn't working. I believe it because one of the variables is an Object, where the other is an Element; does anyone have any advice as to how I can can find a match between these two?
menuID[0] = document.getElementById('menuOne');
menuID[1] = document.getElementById('menuTwo');
menuID[2] = document.getElementById('menuThree');
menuID[3] = document.getElementById('menuFour');
$('.menu').mouseenter(function () {
for (var i = 0; i < 3; i++) {
if(menuID[i] == $(this)){
//this condition is not met, there's an alert which will add more detail in the fiddle
}
}
}
Method document.getElementById returns a DOM element an not a jQuery object. In the mouseenter event handler this refers to a DOM element as well.
So in order to compare them you shouldn't convert this to a jQuery object:
if (menuID[i] === this) { ... }
You want to use jQuery's .is() for this.
if($(this).is(menuID[i])){
A few issues I see here:
One is simply that, in your jsfiddle, the first 4 lines of code that you list aren't running before the bottom block runs. I'm not sure why you have both an init function that you attach to window.onload and a document.ready() function; but you'll want to make sure that init runs.
Secondly; as VisioN said, I think the main issue is that you're trying to compare a jQuery wrapper around a DOM element $(this) with a DOM element (the result of getElementById). As he says, this == menuID[i] will work.
At a design level, why not simply use the id to identify the element? this.id will give you the the id; why not simply use that to determine which menu div you're looking at?
With jquery, I've got the following code:
$('a[data-hello]').click(function(){ = That select all "a" elements with "data-hello".
I'm trying to make this with raw Javascript. I stop here:
document.querySelectorAll("data-hello").onclick = function() {
(btw, theres a way to select all the A elements with data-hello and not all with data-hello? o.O)
But querySelectorAll returns a Array. Because of this, it only works if I determine a position. This way:
document.querySelectorAll("data-hello")[5].onclick = function() {
But I want ALL ELEMENTS, not specific elements, like with jQuery. I cant use jQuery.
It is so simple with Jquery :( I must make a "for" to wade through all the positions in JS? Is this necessary? sorry I do not understand...
What I want to do:
I want to get the data attribute value of the element that is clicked. I use this for this inside the function and, then, I applied another function that add a class in a specific element.
Basically, there is buttons with classes in data attribute value. This classes will be applied to a specific element.
Put the array (actually a NodeList) of elements in a variable and loop through them to set the event handler on each of them. That's what the jQuery methods do to apply something to all elements in a jQuery object. There is no way around the loop, with jQuery it's just hidden within the methods. You can use the same selector syntax as in jQuery with querySelectorAll.
var arr = document.querySelectorAll("a[data-hello]");
var f = function() {
// do something
};
for (var i = 0; i < arr.length; i++) {
arr[i].onclick = f;
}
querySelectorAll accepts a string of comma-separated CSS selectors, just like jQuery, so you can give it the same string: 'a[data-hello]'.
The difference between native and jQuery that you are running into is in calling methods on the elements returned. jQuery returns a jQuery object, which has methods that often loop over all the elements, .click() being one such methods. You need to replicate that with the array of elements that querySelectorAll is returning by looping over the array and applying the same handler to each element's onclick property.
Try this:
var myElements = document.querySelectorAll("a[data-hello]");
Array.prototype.forEach.call(myElements, function (element) {
element.onclick = function () {
// Your onclick handler code goes here.
console.log('clicked', element);
};
});
as simple as that:
var dataElems = document.querySelectorAll("[data-hello]")
for (var i=0;i<dataElems.length;i++) {
dataElems[i].onclick = function(i,v) {
alert(this.innerHTML)
}
}
example http://jsfiddle.net/acrashik/W86k8/
I'm trying to do three things onclick:
have element with id="notes_content" change display:none to display: block
have element with id="oct" change width = "1190px" to width = "550px"
have elements with class="oct_days" change width = "168px" to width = "73px"
Fiddle of full code: http://jsfiddle.net/ascottz/jX3wh/
The first two happen, but the third does not. I suspect it is a syntax error, but can't catch it myself.
getElementsByClassName returns an array of dom elements, it is not a single instance. You must loop over the array and style each element.
Have a look at the updated fiddle.
for( var i = 0; i < days.length; i++ ){
days[i].style.width = "73px";
}
http://jsfiddle.net/jX3wh/4/
document.getElementsByClassName returns somewhat an array of elements, so you cannot simply refer to it as a DOM element in hope that it will work as you refer to each element of the collection (that is possible in jQuery, btw), so you have to use the foreach loop (doesn't matter how are you gonna achieve this -- via simple for(), or for(x in y), or any other way).
I usually use Array.forEach function, but the specific type of an array returned by the document.getElementsByClassName does not have such function in prototype, so you have to use [].forEach.call(inWhat,function(what){}) syntax, or fallback to for(...) syntax.
Check out this: http://jsfiddle.net/jX3wh/1/
Dunno if it works.
Also, what the f is this???
<div onclick="javascript:showDiv();" class="oct_days">
I am really very surprised this works. You should use onclick="showDiv()" instead, I think.
Somebody, please, tell me how does it work!
Hopefully I can explain it well enough. I do
var foo = document.getElementsByTagName('bar');
var len = foo.length;
for(var i=0;i<len;i++){
//Do stuff
}
Inside that for I also want to be able to get an element (specifically a class) that is buried deep within foo[i]. My thought is something like
var whatIWant = document.getElementsByClassName("name").foo[i];
but that doesn't seem to be what I need to do. Am I just not sure on the syntax or do I need to do something completely different?
You've almost got it:
foo = document.getElementsByTagName('bar');
// foo is now a nodelist of all nodes named 'bar'.
for (i = 0; i < foo.length; i++) {
bar = foo[i].getElementsByClassName('baz');
// bar is now a nodelist of all elements with class 'baz' in the dom tree under foo[i].
}
If you were using jquery, it'd be as simple as:
$('bar .baz').each(function() {
$(this). etc...;
});
As far as I'm aware getElementsByClassName is HTML5 (according to this: https://developer.mozilla.org/en/DOM/document.getElementsByClassName) and so using it means that not all browser will support it.
When you grab an Element from the dom, like with document.getElementsByTagName, you get the same method getElementsByTagName and so you can do:
foo[i].getElementsByTagName("...")
For the collection of desired elements, then you can iterate over that array and search for the matching classes.
Also, I recommend using javascript libraries such as jQuery or MooTools, it will make your life easier.