Get all elements containing a class with querySelector - javascript

For changing some styles in a class I'm using querySelector():
el.querySelector('.fa fa-car').style.display = "none";
This works fine for one element but if there are more elements containing this class and I want to change the display to none for all of them, this command only deletes the first occurrence of it leaving the next ones untouched.
I tried to do it with querySelectorAll():
el.querySelectorAll('.fa fa-car').style.display = "none";
But this one returns an error message:
html2canvas: TypeError: Cannot set property 'display' of undefined
any ideas about how to get all the elements containing a specific class and perform an operation on them?

The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Use Document.querySelectorAll() to get all the elements. Then use forEach() to set the style in each element:
var elList = document.querySelectorAll('.fa.fa-car');
elList.forEach(el => el.style.display = "none");
Please Note: Some older version of IE (<8) will not support querySelectorAll(). In that case use
Array.from(document.querySelectorAll('.fa.fa-car'))

querySelectorAll() returns a collection of elements. To change their styling you need to loop through them.
Also note that your selector appears to be invalid. Given the FontAwesome class rules I presume you need to select by both classes. Try this:
Array.from(el.querySelectorAll('.fa.fa-car')).forEach(function() {
this.style.display = "none";
});
Alternatively, as you've tagged the question with jQuery, you could just simplify all that to just:
$('.fa.fa-car').hide();

querySelector only select one element, to select all element you can use querySelectorAll
[].map.call(el.querySelectorAll('.fa fa-car'), n => { n.style.display = 'none'; })

Use method querySelectorAll()
See https://www.w3schools.com/jsref/met_document_queryselectorall.asp
You are getting error because querySelectorAll returns an array.Iterate over it and then use style.display

You could do all your operation by iterating the occurence of this class and of course by help of some if clauses.
$('.fa.fa-car').each(function(){
$(this).css('color','white');
})

Related

documents get elements by classname apply to all element

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>

JS es6 on click add class to another element

I'm trying to show a div when another button has been clicked.
Unfortunately the site i'm using doesn't use jquery but has babel.js installed.
This is the HTML of the button the user is clicking
<button id="ba-Calculate" class="button">Calculate</button>
And this is the HTML for the button I would like to display
<button class="js-find-a-mortgage button u-margin-top-small" style="display: none;">Find a mortgage</button>
I've added a style of display none to hide the element.
This is what i've come up with so far.
var el = document.querySelector('#ba-Calculate');
el.onclick = function() {
document.getElementsByClassName('js-find-a-mortgage').style.display = 'block';
}
Any suggestions or where to read up on how I can crack this would be great.
I appreciate the feedback, thank you.
document.getElementsByClassName returns an array. So, you need to fetch the first element (I believe you have only one element with that class in the DOM) and add the style.
Try using
document.getElementsByClassName('js-find-a-mortgage')[0].style.display = 'block';
var trigger = document.querySelector('#ba-calculate')
var el = document.querySelector('.js-find-a-mortgate')
trigger.addEventListener('click', function () {
el.style.display = 'block'
})
getElementsByClassName returns an array like object
The getElementsByClassName method of Document interface returns an
array-like object of all child elements which have all of the given
class names. When called on the document object, the complete document
is searched, including the root node. You may also call
getElementsByClassName() on any element; it will return only elements
which are descendants of the specified root element with the given
class names.
Using querySelector will grab the first instance of a node matching that class name. You can then use the code you already had.
If you want to add class, I assume you need to use classList method add:
For example to add for your element class 'hidden':
document.getElementsByClassName('js-find-a-mortgage')[0].classList.add('hidden');
To see all classes use: document.getElementsByClassName('js-find-a-mortgage')[0].classList
https://www.w3schools.com/jsref/prop_element_classlist.asp

Change HTML action="" using JavaScript

How can I change the string inside action="somthing" I've tried using
document.getElementsByClassName
but it doesn't seems to change anything.
My HTML
......
.........
<div class="my_button button" action='play_car'></div>
.....
......
My Javascript
document.getElementsByClassName('my_button').action = "play_boat";
.......
......
I've also tried
HTML
<div id="test" class="my_button button" action='play_car'></div>
Javascript
var a= document.getElementById('test');
console.log(a);
It just returns null
"get element-s by class name" returns a collection, not a single element.
Returns an array of all child elements which have any of the given class names. When called on the document object, the complete document is searched, including the root node.
Assuming that there is only a single element returned, then:
var elementsWithClass = document.getElementsByClassName('my_button')
elementsWithClass[0].action = "play_boat";
However, it may be more appropriate to use a loop - class names are generally designed to be used with multiple elements, and IDs (along with getElementById) for singular/unique elements.
Unfortunately, getElementsByClassName is not supported in even as "recent" a browser as IE8. To handle this, use a cross-browser library (jQuery or your preference) or a polyfill.
getElementsByClassName will return an array of all elements. Use document.getElementById if you want to address only one element. Also getElementsByClassName isn't supported by older browser. If that's an issue, you can use jQuery instead.
If you have only one element with this class name, you can get the first item:
document.getElementsByClassName('my_button')[0].action = "play_boat";
if you have many, iterate over them:
for (var i in document.getElementsByClassName('my_button')) {
document.getElementsByClassName('my_button')[i].action = "play_boat";
}
Please, check if the place of the javascript code is after the elements with the class "my_button".

How to select text by tag name in element?

I need to select title which is in div wrapped by h2, so i do something like this this.getElementsByTagName('h2') where this is current div in which is h2 - it returns current h2 element, but when i trying to get innerHTML or innerText it return null. What am I doing wrong?
it returns current h2 element, but when i trying to get innerHTML or innerText it return null. What am I doing wrong?
getElementsByTagName returns a NodeList, not an element. The list doesn't have innerHTML, but each of its elements does, e.g.:
var list = this.getElementsByTagName('h2');
if (list[0]) {
title = list[0].innerHTML;
}
Or if you're sure that it will exist:
title = this.getElementsByTagName('h2')[0].innerHTML;
...but that will throw an exception if there are no h2's found.
No, this.getElementsByTagName('h2') returns an array of elements with tag name h2.
You have to iterate the array and access the correct element you want.
Two things:
You should capture the first element of the node list that's returned by getElementsByTagName():
var h2 = this.getElementsByTagName('h2')[0];
Different browsers use different properties to retrieve the tag contents:
var title = h2.textContent || h2.innerText || null;
Yes, you have done a small mistake. Because , this.getElementByTagName('h2') will return you a list ( of tags).
Being your tag is the first element as [0]
you can use
var v= this.getElementsByTagName('h2');
var yourdata=v[0].innerHTML;
As the other answers state getElementsByTagName returns an array.
Another option would be to use querySelector (supported only by modern browsers so check what you need to support first)
Running querySelector on this page gives the following:-
window.document.querySelector('h1').innerHTML //#>
"How to select text by tag name in element?"
querySelector
querySelectorAll

get firstChild of div

I am trying to get the text of the span element. I have tried two methods using querySelectorAll and getElementByClassName but both give me the error "Uncaught TypeError: Object # has no method 'getElementsByTagName'" how do I go about getting the text of the span element?
javascript
var interstitial;
// 1st attempt
interstitial = document.querySelectorAll('div.top_bg').getElementsByTagName("span");
// 2nd attempt
interstitial = document.getElementByClassName('top_bg')[0].getElementsByTagName("span");
if (interstitial) {
console.log(interstitial[0].firstChild.innerHTML);
}
html
<div class="top_bg">
<span style="font-size:14px;line-height:30px">The text I am trying to get.</span>
</div>
Include the span in the query
interstitial = document.querySelectorAll('div.top_bg span');
document.querySelectorAll('div.top_bg') returns a collection so you'll have to select a node then apply getElementsByTagName
Also its getElementsByClassName not getElementByClassName notice the Elements
http://jsfiddle.net/dRvDt/1/
You are getting the error because the object returned by querySelectorAll is a NodeList, and NodeLists don't have a getElementsByTagName method. You should do something like:
var node, nodeList, spans
if (document.querySelectorAll) {
nodeList = document.querySelectorAll('div.top_bg');
node = nodeList[0];
if (node) {
spans = node.getElementsByTagName('span');
}
}
spans is now a NodeList of the spans contained in the first element of the first NodeList, if there was one. The first one will be at spans[0], and so on.
if you can use the jquery, you can look for the span html easy:
$("div.top_bg>span").firstChild().html();

Categories