How to add a class to a class with Javascript not JQ - javascript

trying to figure out how to find a class and add a class to it using javascript. all example online are with id , I need to find the classs. Any idea guys?
I am adding a class once the page is loaded.
<nav class="menu custom-effect" id="customMenu">
<ul class="menu-list">
<li class="menu-item current_page_item">Home</li>
<li class="menu-item">Who we are</li>
<li class="menu-item">What we offer</li>
<li class="menu-item">Our news</li>
<li class="menu-item">Contact us</li>
</ul>
</nav>
<script>
document.addEventListener("DOMContentLoaded", function(){
// document.getElementById("current_page_item").classList.add( "current-page");
var element = document.getElementById("customMenu");
var elementClass = element.getElementsByClassName("current_page_item");
elementClass[0].ClassNames.add("extraClass");
console.log(element);
console.log(elementClass);
});
</script>

When you search for a class you get an array I understood and not just one element, so you need to referece the element u want as it picks up all the classes.
the answear to the code is
<script>
var element = document.getElementById("menu-main-menu");
var elementClass = element.getElementsByClassName("current_page_item");
elementClass[0].classList.add("foo");
</script>
classList implementation of these methods is super easy now that I understood the issue:
// adds class "foo" to el
el.classList.add("foo");
// removes class "bar" from el
el.classList.remove("bar");
// toggles the class "foo"
el.classList.toggle("foo");
// outputs "true" to console if el contains "foo", "false" if not
console.log( el.classList.contains("foo") );
// add multiple classes to el
el.classList.add( "foo", "bar" );

Related

How to keep a menu-item selected in html with javascript

This is my html code. How can I keep a menu-item (link to another page) selected when I'am browsing ? I'd like to do it with javascript. Thank you in advance.
<ul class="header-menu" id="nav">
<li class="menu-item">HOME</li>
<li class="menu-item">NEWS</li>
<li class="menu-item">TOUR DATES</li>
<li class="menu-item">GALLERY</li>
<li class="menu-item">ABOUT</li>
</ul>
There are multiple ways to achieve that effect. Let's first state that you have an "active" class that you can use on the menu items that will make them pop out, how would you go about applying that class?
First of all, I would assign a specific class or id to all the menu items, to make them easy to reference within the css (or javascript).
Let's say that now your situation is like this:
<ul class="header-menu" id="nav">
<li class="menu-item home-item">HOME</li>
<li class="menu-item news-item">NEWS</li>
<li class="menu-item tour-item">TOUR DATES</li>
<li class="menu-item gallery-item">GALLERY</li>
<li class="menu-item about-item">ABOUT</li>
</ul>
Now, with javascript, you could do it like this:
// Get the page name
let pathArray = location.pathname.split("/");
let page = pathArray[pathArray.length-1];
// Get all menu items and convert them to an Array
let menuItems = document.querySelectorAll(".header-menu .menu-item");
menuItems = new Array(...menuItems);
let lookFor = "";
// Based on the page, set the variable lookFor as the identifying class
switch (page) {
case "home.html":
lookFor = "home-item";
break;
case "news.html":
lookFor = "news-item";
break;
// ...
}
// Get the element that contains the class
let item = menuItems.filter( (item) => item.classList.contains(lookFor) )[0];
// Set the "active" class on the element
item.classList.add("active");
Here you can check out a codesandbox with the working code.

Change CSS of single 'LI' array element using Jquery

I am new to Javascript and jQuery.
I made a simple image slider and encounter an issue with jQuery.
I have the following html for my list of images:
<div id = "slider-auto">
<ul class= "slides">
<li class = "slide"><img src="Images/one.jpg"/></li>
<li class = "slide"><img src="Images/two.jpg"/></li>
<li class = "slide"><img src="Images/three.jpg"/></li>
<li class = "slide"><img src="Images/four.jpg"/></li>
<li class = "slide"><img src="Images/five.jpg"/></li>
<li class = "slide"><img src="Images/one.jpg"/></li>
</ul>
</div>
I am trying to store the 'li' elements inside a variable(array) and change the CSS of a specific 'li' element using jQuery.
The following works fine:
$(document).ready(function(){
$slideContainerMan = $('#slider-auto');
$mySlides = $slideContainerMan.find('.slide');
$mySlides[0].style.display = "block";
})
If I use jQuery to access the CSS of the first list element I get an error:
$(document).ready(function(){
$slideContainerMan = $('#slider-auto');
$mySlides = $slideContainerMan.find('.slide');
$mySlides[0].css('display','block');
})
The above code produces '$mySlides[0].css is not a function'.
I am assuming this is not the correct way of accessing array elements using jQuery.
How do I use jQuery to access 'li' elements singularly?
Thanks for your help in advance.
The numeric properties on a jQuery object reference DOM elements, not jQuery objects.
If you want to call jQuery methods, you have to wrap the element with a jQuery object.
$( $mySlides[0] ).css(...)
$mySlides[0] returns the li element, and not the jquery object, thus you can't use the css function on it.
What you can do is use the jQuery constructor on that element $(element) or use the first() function to get the wrapped element:
$(document).ready(function(){
$slideContainerMan = $('#slider-auto');
$mySlides = $slideContainerMan.find('.slide');
// option 1:
$($mySlides[0]).css('display','block');
// option 2:
$mySlides.first().css('display','block');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "slider-auto">
<ul class= "slides">
<li class = "slide"><img src="Images/one.jpg"/></li>
<li class = "slide"><img src="Images/two.jpg"/></li>
<li class = "slide"><img src="Images/three.jpg"/></li>
<li class = "slide"><img src="Images/four.jpg"/></li>
<li class = "slide"><img src="Images/five.jpg"/></li>
<li class = "slide"><img src="Images/one.jpg"/></li>
</ul>
</div>

Assign child element to variable for click function

I have a WordPress generated menu that has this structure:
<li id="menu-item-407" class="smoothAboutScroll menu-item menu-item-type-custom menu-item-object-custom menu-item-407">
About Us
</li>
I want to target the <a> child and store it in a variable, so then I can create a onclick function that runs when the <a> element is clicked on.
This is what I have:
var aboutLink = $('#menu-item-407').children();
$('aboutLink').on('click', function() {
// run function
})
$('aboutLink') is looking for a <aboutLink></aboutLink> element that doesn't exist.
That selector string has nothing to do with the variable aboutLink which is now a jQuery object itself
Try
var aboutLink = $('#menu-item-407 > a');
aboutLink.on('click', function() {
// run function
})
Give the <a> element an id and then target it using jquery?
var myElement = $('#myLinkId');

How to select element by 'role' attribute and filter by class with vanilla JS?

Markup:
<ul>
<li role="presentation" class="active">
How to Install for iPad
</li>
<li role="presentation">
How to Install for Mac
</li>
<li role="presentation">
How to Install for PC
</li>
</ul>
When I use document.querySelectorAll('[role="presentation"]'); the result is array
[li.active,li,li]
How can I remove .active class and attach it to any other of these li with plain JS w/o JQuery the more simplest way?
Try this:
// remove active class from all elements
document.querySelectorAll('[role="presentation"]').forEach(function (el){
el.classList.remove("active");
});
// add class 'active' to last element
document.querySelectorAll('[role="presentation"]:last-of-type')[0].classList.add("active")
Notes:
'classList' will not work in IE9;
I think you have to modify adding class row, depending on your needs.
You can try something like this:
var ele = document.querySelectorAll('[role="presentation"]');
ele[0].classList.remove("active"); //Remove active class for first element
ele[ele.length- 1].classList.add("active"); //Apply active class for last element
console.log(ele)
var eleLi = document.querySelectorAll('[role="presentation"]');
for (var i = 0; i < eleLi.length; i++) {
//remove class active
eleLi[i].classList.remove('active');
}
//x is an index of li that you want to add the class. Such as 0,1,2
var x = eleLi.length - 1;
//add class active
eleLi[x].classList.add('active');

Check page title is contained within link attribute and assign active class using jQuery

I'm building a jQuery function to change the colour of the link of my navigation bar. I want to identify the data attribute of a link in the navigation bar and compare it to the current title of the page.
I then want to see if the current page title contains the anchor tags data attribute and if so addClass("active"); if the result is true. A key requirement is it to not match case as well.
Here is my corresponding html and javascript
<ul class="top nav">
<li><a class="first" href="http://www.fishwebsite/" name="link" data-index="Home">Home</a></li>
<li>About us</li>
<li>Our boats</li>
<li>Product list</li>
<li>Recipes</li>
<li>Contact us</li>
</ul>
And the javascript currently is
var current_title = (document).attr("title");
$("a[name=link]").each(function () {
var a = $("a[name=link]").attr("data-index");
//returns true or false...
var exists = current_title.test(a);
if(exists) {
$(a).addClass("active");
}
else {
//false statement..do whatever
}
});
Can someone help me along? I have a CSS style for an active link which will be different to usual nav items hence giving the impression its the 'active' page on the site.
Change to $(this) in each function since, you are selecting each item.
var current_title = (document).attr("title");
$("a[name=link]").each(function () {
var a = $(this).attr("data-index");
//returns true or false...
var exists = current_title.test(a);
if(exists) {
$(this).addClass("active");
}
else {
//false statement..do whatever
}
});
Try this,Wrap your script inside document ready. and I changed your functions little bit.
<script>
$(document).ready(function(){
var current_title = $(document).attr("title");
$("a[name=link]").each(function () {
var a = $(this).attr("data-index");
//returns true or false...
var exists = current_title.indexOf(a)>0;
if(exists) {
$(a).addClass("active");
}
else {
//false statement..do whatever
}
});
});
</script>
I have now fixed the issue thanks to both posts above. Here is the complete HTML and JS.
<ul class="top nav">
<li><a class="first" href="http://www.fishwebsite/" name="link" data-index="Home">Home</a></li>
<li>About us</li>
<li>Our Boats</li>
<li>Product list</li>
<li>Recipes</li>
<li>Contact us</li>
</ul>
And the Javascript
$(document).ready(function() {
var current_title = $(document).attr("title");
$("a[name=link]").each(function() {
var a = $(this).attr("data-index");
var exists = current_title.indexOf(a)>0;
if(exists) {
$(this).addClass("active")
}
else {
// $(this).removeClass('active');
}
});
});
Adding $(this) instead of (a) was a great tip as it singled out the link in question and Nishans addition of >0 finished off the working code.
Drawbacks
Case sensitivity. The data-index value must match the case of the title exactly or the active link will not be assigned.
Longer anchor tags with the addition of a name attribute and data-index.
Advantages
An efficient way to assign an active link with jQuery and title and data-index can be matched up in case very easily when building websites. No server side, messy PHP intervention to assign an active link.

Categories