Adding class to an element got by classname - javascript

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>

Related

changing css custom properties in javascript

i've a JSX module(card.jsx) which is call in another component to create 5 instances of this module(card.jsx).
import card.css
...
<div className='cistern'>
<div className="shape">
<div className="wave"></div>
</div>
</div>
in my card.css, i have a custom property call filled.
.wave {
position: absolute;
--filled: 20%;
in my card.jsx i try to set different value for the css custom variable "filled".
React.useEffect(() => {
var cisternProperty = document.querySelector( '.wave' )
cisternProperty.style.setProperty('--filled', showFilledRoundString)
console.log('show Tank Level', showFilledRoundString)
}, [])
only the first instance use the new value, all other instance used the default "filled" value set in the css file.
what's happening? what could be the workaround?
thanks
To change the CSS property for every instance of an element in the .wave class you can either change the property in some common ancestor element rather than in the .wave elements themselves or you can go through all the .wave elements change their property.
So instead of using querySelector, which gives you only the first element in that class, use querySelectorAll which gives you a collection of all the elements in that class. You can then loop through them setting the CSS variable individually for each one:
var cisternProperties = document.querySelectorAll( '.wave' );
cisternProperties.forEach( cisternProperty => {
cisternProperty.style.setProperty('--filled', showFilledRoundString);
});

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

jQuery cannot find class element from some html returned via ajax call

I am running an ajax call that returns some HTML as a string. For the purpose of this question I will call this <div class='abc'>ABC123</div> when I get this back I want to check and see if the class "abc" has a value and what that value is. However when I run a .find() I cannot find the class, I can find the div, but not the specific class. Just using the div is not adequate because in the real live code the HTML is very complex and has many divs and classes. Below is some JS that illustrates my point.
var x = "<div class='abc'></div>";
$(x).hasClass("abc"); // returns true
$(x).find(".abc"); // Returns empty array
Why is it that the first line returns true, but the selector cannot find the element?
Thanks!
Because $x is the div with class abc.
jquery .find() tries to find any children within the div.abc with class abc which it won't find.
This is more like it.
var x = "<div class='abc'><div class='def'></div></div>";
$(x).hasClass("abc"); // returns true
$(x).find(".def"); // returns $('div.def')
When we append html element to the page, sometimes JQuery can't find this element due to parent and child relationship.
For example: a button having class submit inside a div having id append_area and we want to run a function on click on this button. Then we can use the below code.
HTML Code:
<div id="append_area">
</div>
Jquery Code:
$("#results").delegate('.submit', 'click', function(){ });

Element not reacting to JQuery Click

I have added Elements using Jquery inside PHP after loading them from the database. Each button has two classes, one controlling the GUI and another controlling the Click for particular button. The code is as under
echo "<script type='text/javascript'>$('.main').append('<button class=b_ui b$index>Change</button>'); </script>";
Now if I check the classes from Inspect Element perspective of the browser, it shows 2 classes. But when I click on it and get class of element using this code
$('.b_ui').click(function()
{
cls = $(this).attr('class');
alert('no. '+cls);
}
It shows only first class (GUI) and not the other which I want to use for handling click.
Any help ?
Put quotes around the class attribute. <button class=\"b_ui b$index\">Change</button>
You should use "on" method:
$(document).on('click', '.b_ui', function() {
cls = $(this).attr('class');
alert('no. '+cls);
});
When adding elements dynamically to the DOM, they are not accessible by jQuery like an element which was there at page load. say you have this div:
<div id="div"></div>
and you add some content with jQuery so it now looks like this:
<div id="div"><span id="span"></span></div>
you cannot refer directly to the span using jQuery with $('span[id=span]'), you have to target a containing element then filter which contained element you want:
$('#id').on('click','span',function(){});

Using javascript to set an HTML class name

Is it possible to put a javascript function call in place of a HTML class name so that the class can be set based upon the results of the function? For example, something like:
<a class="fSetClass(vName)" ....
which would call a function named fSetClass() and receive back a valid CSS class name based upon the parameter vName passed with it.
Thanks
No, it's not possible to do what you're asking from within the HTML. Though, you can use JavaScript to add the class to it afterward.
Smth like this, if in short way
document.onload = function(){
document.getElementById('your-element-id').className = fSetClass(vname);
}
No but what you can do is use jquery to get the item and then add or remove class names from it:
HTML
<div class="my-class">My Content</div>
jQuery
// will produce <div class="my-class added-class">My Content</div>
var addClass = 1;
if(addClass == 1) {
$(".my-class").addClass("added-class");
}
else
{
$(".my-class").removeClass("removed-class");
}
Only the on* event handler attributes are evaluated as JavaScript code, the other attributes are not.
As already said, you have to assign the class normally with JavaScript. Assuming you have a reference to the element (element), you have to assign the class to the className [MDN] property:
element.className = fSetClass(vname);
If you use jquery, you can set the class by using .attr():
$(document).ready(function() {
function fSetClass(vName){
$("#element_id").attr('class', vName);
}
fSetClass('className');
});
If you use jQuery, you can use the addClass function
$(element).addClass('add-this-class');
If you want to set the class instead, use attr:
$(element).attr('class','add-this-class');

Categories