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
Related
Trying to add a class to an element, I need to get by class name. Any idea why it is not working? (Using Wordpress Code Snippets in case someones wondering)
<?php
add_action( 'wp_head', function () { ?>
<script>
var myButton = document.getElementsByClassName("menu-toggle mobile-menu");
myButton.classList.add(".teststyle");
</script>
<style>
.teststyle {}
</style>
<?php } );
You're querying for multiple elements, as class names are not unique, therefore you need to loop through them. Also, you don't need the selector-specific dot to specify a class when using classList.add.
This snippet should work, if your element has both the classes menu-toggle and mobile-menu:
document.querySelectorAll(".menu-toggle.mobile-menu").forEach((element) => element.classList.add("teststyle"))
If the element with the class mobile-menu is a child of the element with the class menu-toggle, try this:
document.querySelectorAll(".menu-toggle.mobile-menu").forEach((element) => element.classList.add("teststyle"))
Edit:
As you're adding the script into the head, it'll be run before the HTML elements are loaded, so you need to defer the execution until the DOM is loaded.
You can either add the script after the elements in the DOM, or use the DOMContentLoaded event, e.g. like this:
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll(".menu-toggle.mobile-menu").forEach((element) => element.classList.add("teststyle"))
});
Normally the response of a document.getElementsByClassName(...) is a NodeList. So basically you have to assign the value to a specific index of that NodeList.
In this case you should be getting an error in console that says something like
TypeError: Cannot read property 'add' of undefined
That happens because your NodeList doesn't have an element called classList and because of that the add function doesn't exist in that context.
Once you get the elements by class you get a NodeList element with all the corresponding elements and what you can do is:
myButton[0].classList.add("teststyle");
Also, here you don't need the point prefix for the class.
Here's an example.
var myButton = document.getElementsByClassName("menu-toggle mobile-menu");
console.log(myButton);
console.log(myButton[0]);
myButton[0].classList.add("test-class");
.test-class {
color: red;
}
<button class="menu-toggle mobile-menu">Button</button>
I wanted to copy an entire row including its' siblings and contents on button click. When I click the button the element, it appears in the console but doesn't append to the page. This is my code:
It doesn't show any error messages. I've tried innerHTML/outerHTML or append() it doesn't work.
$(document).ready(function() {
$('#addSubFBtn').on('click', function() {
var itm = document.getElementById("trFb");
var wrapper = document.createElement('div');
var el = wrapper.appendChild(itm);
document.getElementById("tbFb").append(el);
console.log(el);
});
});
Seems like what you're trying to do is clone the item after you get it from your document. W3schools website explains how to accomplish this. Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp
Once you clone the node, [appendchild] should work as intended
Not sure (as said without seeing related HTML) but i see flaw in your logic:
var itm = document.getElementById("trFb");
still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place.
using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be:
var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb"));
as shown here to remove element you've to use method on to parent element.
So you can add it to any other element existing.
For more specific use or element created in global JS variable (such an createElement not yet appended) you can see :document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
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');
})
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".
I googled and googled and I concluded that it's very hard to get answer on my own.
I am trying to use jquery or JavaScript to get a property of clicked element. I can use "this.hash" for example - it returns hash value I presume.
Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?
jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.
JavaScript documentation? - is there even one comprehensive one? again please a link.
DOM documentation? - the one on W3C or where (link appreciated).
And what is this.hash? - DOM JavaScript or jQuery?
In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:
Example: http://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.
There are jQuery methods that do this as well, like .attr().
Example: http://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.
This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.
jQuery
$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});
Javascript
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}
Try it out
http://jsfiddle.net/M2Wvp/
Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
this supports on clicking anywhere of the page. if the element you clicked doesn't have a class name, it will return null or empty string.
$('#ele').click(function() {
alert($(this).attr('class'));
});
And here are all of the attribute functions.
http://api.jquery.com/category/attributes/
You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.
Then you can iterate all of them and find the one you want.
window.onclick = function(e) {
var classList = e.srcElement.className.split(/\s+/);
for (i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
}
jQuery does not really help you here but if you must
$(document).click(function(){
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item==='someClass') {
//do something
}
});
});
There's a way to do this without coding. Just open the console of your browser (f12?) and go to element you want. After that, hover or click the item you want to track.
Every change done on the DOM will be for a few seconds marked (or lightened) as another color on the console. (Watch the screen capture)
On the example, each time I hover a "colorItem", the 'div' parent and the "colorItem" class appears lightened. So in this case the clicked class will be 'swiper-model-watch' or 'swiper-container' (class of the lightened div)