For example:
var inputs = document.querySelectorAll('input[type="checkbox"]');
I want to set the checked to true on all inputs. Can this be done like in jQuery, without using a for loop?
querySelectorAll returns a NodeList. You will need to iterate over the list to change each item in it (jQuery loops over the entire collection too in the background using .each)
You can either use a loop (for, while, etc) or you could use the forEach method on the Array prototype
https://developer.mozilla.org/en-US/docs/DOM/NodeList#Workarounds
No, this cannot be done without some form of iteration over the nodes. jQuery iterates over the nodes as well, it just hides it from the user.
The closest that comes to jQuery-like style is using .forEach [MDN] in browser where it is supported:
[].forEach.call(inputs, function() {
this.checked = true;
});
without using a for loop
At some point, you're going to need some form of loop. Are you just hoping to abstract it?
NodeLists are Array-like, so you can call or apply methods from Array.prototype, including iterators like forEach(). An example from MDN:
Another approach without extending the DOM:
var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function(link){ // works in most browsers (please document here if you find browsers where it doesn't)
link.style.color = '#0F0';
});
But note that even forEach() depends on a loop (while in this case).
Using pure JavaScript you can use the querySelectorAll() function as below:
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for(var i=0; i<checkboxes.length; i++) { checkboxes[i].checked = true; }
Unfortunately this doesn't avoid looping which I know you wanted to avoid and It also doesn't have perfect cross browser compatibility as can be checked here with IE 8 only being able to hook on to CSS 2.1 selectors and Pre IE8 not being supported at all but it's the best that can be done without using lots of code and avoiding jQuery.
I know you want to avoid jQuery but, if you change your mind you can try the following:
$('input[type="checkbox"]').attr('checked', 'checked')
This should hook on to any checkbox input and set its attribute to checked using the jQuery attr() function.
If this doesn't work try giving your checkboxes their own class name such as checkbox and try like as follows:
$('.checkbox').attr('checked', 'checked')
This would help with compatibility issues and would avoid looping but if you don't want to go the jQuery route then please ignore.
Related
element.classList is of DOMTokenList type.
Is there a method to clear this list?
I'm not aware of a "method" in the sense of a "function" associated with classList. It has .add() and .remove() methods to add or remove individual classes, but you can clear the list in the sense of removing all classes from the element like this:
element.className = "";
With ES6 and the spread operator, this is a breeze.
element.classList.remove(...element.classList);
This will spread the list items as arguments to the remove method.
Since the classList.remove method can take many arguments, they all are removed and the classList is cleared.
Even though it is readable it is not very efficient. #Fredrik Macrobond's answer is faster.
View different solutions and their test results at jsperf.
var classList = element.classList;
while (classList.length > 0) {
classList.remove(classList.item(0));
}
Here's another way to do it:
element.setAttribute("class", "")
Nowadays, classList is preferred to (remove|set)Attribute or className.
Pekaaw's answer above is good, 1 similar alternative is to set the DomTokenList.value
elem.classList.value = ''
Another option is to simply remove the class attribute:
elem.removeAttribute('class')
I recommend not using className as classList could result in faster DOM updates.
The remove() method of DOMTokenList (which is what classList is) can take multiple arguments - each a string of a classname to remove (reference). First you need to convert the classList to a plan array of classnames. Some people use Array.prototype.slice() to do that, but I'm not a fan and I think a for loop is faster in most browsers - but either way I have nothing against for loops and the slice often feels like a hack to me. Once you have the array you simply use apply() to pass that array as a list of arguments.
I use a utility class I wrote to accomplish this. The first method is the one you are looking for, but I'm including slightly more for your reference.
ElementTools.clearClassList = function(elem) {
var classList = elem.classList;
var classListAsArray = new Array(classList.length);
for (var i = 0, len = classList.length; i < len; i++) {
classListAsArray[i] = classList[i];
}
ElementTools.removeClassList(elem, classListAsArray);
}
ElementTools.removeClassList = function(elem, classArray) {
var classList = elem.classList;
classList.remove.apply(classList, classArray);
};
ElementTools.addClassList = function(elem, newClassArray) {
var classList = elem.classList;
classList.add.apply(classList, newClassArray);
};
ElementTools.setClassList = function(elem, newClassArray) {
ElementTools.clearClassList(elem);
ElementTools.addClassList(elem, newClassArray);
};
Please note that I have not thoroughly tested this in all browsers as the project I am working on only needs to work in a very limited set of modern browsers. But it should work back to IE10, and if you include a shim (https://github.com/eligrey/classList.js) for classList, it should work back to IE7 (and also with SVGs since Eli Grey's shim adds support for SVG in unsupported browsers too).
An alternative approach I considered was to loop backwards through the classList and call remove() on classList for each entry. (Backwards because the length changes as you remove each.) While this should also work, I figured using the multiple arguments on remove() could be faster since modern browsers may optimize for it and avoid multiple updates to the DOM each time I call remove() in a for loop. Additionally both approaches require a for loop (either to build a list or to remove each) so I saw no benefits to this alternative approach. But again, I did not do any speed tests.
If somebody tests speeds of the various approaches or has a better solution, please post.
EDIT: I found a bug in the shim which stops it from correctly adding support to IE11/10 for multiple arguments to add() and remove(). I have filed a report on github.
I have a javascript function MyFunc() that does what it has to do with id="item_for_MyFunc".
In the function there is a
var elem = document.getElementById("item_for_MyFunc");
and html body has:
<body onload="MyFunc()">
<p id="item_for_MyFunc">
Everything works, but I want to use this function for several items on the page. That's why I should use <p class="item_for_MyFunc"> several times on the page to be processed by this function, so using id is not a solution.
What changes in the function should be done so it could be changed for class="item_for_MyFunc"?
So what you're doing there is pretty simple. Let me give you a slightly more robust version:
document.addEventListener('load', function(){
var elements = document.querySelectorAll('.myClassName');
for(var i=0, len=elements.length; i<len; i++){
MyFunc.call( elements[i] );
}
}, false);
So old versions of IE, 6 and 7 to be specific, don't have querySelectorAll. I'm assuming you aren't worried about them. If you are, there's other ways to do this and I can show you how if you need.
Basically we're giving all of your elements a class of 'myClassName', and querySelectorAll finds all of them and returns an array of DOM elements.
We then iterate through the list, and execute MyFunc on each of those elements.
Edit
So one key principal of writing good javascript is to separate the js code from your html markup as much as possible. You should almost never use inline event handlers like onload="myFunc" anymore. Use event handlers written in the js itself.
If you have the option, you should use the jQuery library. It makes a lot of this stuff incredibly easy, has great support for very old browsers, and is used on hundreds of thousands of websites.
document.getElementsByClassName
would return an array of all HTML elements using the class name. Iterate over the results and you are set. Supported in all browsers except IE <= 8, FF < 3. Works just like document.querySelectorAll (works in IE >= 7, FF >=3.5)
Refer:
http://quirksmode.org/dom/w3c_core.html#gettingelements
for compatibility chart.
You could try:
var elems = document.getElementsByClassName('myClass');
I've not used that one before, but you could use jQuery as that's even simpler;
var elems = $('.myClass');
I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}
I have a snippet of code like this:
var profileLinks = new Array();
for (var i = 0; i<searchResult.length; ++i)
{
var profileLink=searchResult[i].getElementsByTagName("a");
profileLinks[i]=profileLink[0].href;
alert(i+1+" of "+searchResult.length+" "+profileLinks[i]);
}
It seems like I should be able to make it more concise by using this:
//alternate construction (why doesn't this work?)
var searchResult = document.getElementsByClassName("f_foto").getElementsByTagName("a");
What's wrong here?
Use querySelectorAll() instead:
var searchResult = document.querySelectorAll(".f_foto a");
IE 8 supports querySelectorAll() but not getElementsByClassName(), so this should give you better compatibility too.
For full compatibility, stick to your original code or use a library like jQuery.
document.getElementsByClassName("f_foto")
returns a selection, therefore you cannot chain functions to it. You need to specify an element directly not a whole selection, for example this would work correctly.
document.getElementsByClassName("f_foto")[0].getElementsByTagName("a");
Because document.getElementsByClassName("f_foto")[0] points to an object and not to a selection of objects.
This is why we have libraries - or even modern browsers. You are looking for the css selector $('.f_foto a') in jQuery, or $$('.f_foto a') in Prototoype/Chrome
You call getElementsByTagName on a node, not an array, which is what is returned by getElementsByClassName.
I believe that getElementsByTagName can only be applied to an element node, but the result of getElementsByClassName is surely going to be a list of nodes. You'll either have to pick one ([0]?) or iterate over the collection (make sure it's not empty!).
I got a div, and there i got some childnodes in undefined levels.
Now I have to change the ID of every element into one div. How to realize?
I thought, because they have upgoing IDs, so if the parent is id='path_test_maindiv' then the next downer would be 'path_test_maindiv_child', and therefore I thought, I'd solve that by wildcards, for example:
document.getElementById('path_test_*')
Is this possible? Or are there any other ways?
Not in native JavaScript. You have various options:
1) Put a class and use getElementsByClassName but it doesn't work in every browser.
2) Make your own function. Something like:
function getElementsStartsWithId( id ) {
var children = document.body.getElementsByTagName('*');
var elements = [], child;
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (child.id.substr(0, id.length) == id)
elements.push(child);
}
return elements;
}
3) Use a library or a CSS selector. Like jQuery ;)
In one of the comments you say:
(...) IE is anyway banned on my page, because he doesn't get it with CSS. It's an admin tool for developer, so only a few people, and they will anyway use FF
I think you should follow a different approach from the beginning, but for what it's worth, in the newer browsers (ok, FF3.5), you can use document.querySelectorAll() with which you can get similar results like jQuery:
var elements = document.querySelectorAll('[id^=foo]');
// selects elements which IDs start with foo
Update: querySelectorAll() is only not supported in IE < 8 and FF 3.0.
jQuery allows you to find elements where a particular attribute starts with a specific value
In jQuery you would use
$('[id^="path_test_"]')
Try this in 2019 as a wildcard.
document.querySelectorAll("[id*=path_test_]")
I don't think so wildcards are allowed in getelementById.
Instead you can have all the child nodes of your respective DIV using:
var childNodeArray = document.getElementById('DIVID').childNodes;
This'll give you an array of all elements inside your DIV. Now using for loop you can traverse through all the child elements and simultaneously you can check the type of element or ID or NAME, if matched then change it as you want.
You should not change ID of element to ID of other existing element. It's very wrong, so you better re-think your core logic before going on.
What are you trying to do exactly?
Anyway, to get all elements with ID starting with something, use jQuery as suggested before, if you can't it's also possible using pure JavaScript, let us know.