I am using two navbars. Both of them share a single class ('navbar-item'). Basically both navbars do the same things.
E.g.
navbar-1
<a class="navbar-item" href="#Services">
<span class="icon"><i class="fas fa-clipboard-list"></i></span>
<span>Services</span>
</a>
<a class="navbar-item" href="#Delivery">
<span class="icon"><i class="fas fa-shipping-fast"></i></span>
<span>Delivery</span>
</a>
<a class="navbar-item" href="#Contact">
<span class="icon"><i class="fas fa-shipping-fast"></i></span>
<span>Contact</span>
</a>
navbar-2
<li class="navbar-item"></li>
<li class="navbar-item"></li>
<li class="navbar-item"></li>
I am looking to add/remove another class name ('current') when clicked. I want to add this new class name ('current') to both navbars. So when "Services" is clicked, in both navbrs only the "Services" should have the class current. When "Delivery" is clicked, in both navbrs only the "Delivery" should have the class current.
I am looking for a pure js solution (no jQuery). This is what I have so far.
This passes the new class name (current) only to the first navbar.
var btns = document.getElementsByClassName("navbar-item");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("current");
current[0].className = current[0].className.replace(" current", "");
this.className += " current";
});
}
Note:- this is the way you can detect selected div using that you can toggle(add/remove) class based on the selected element.
var div1 = document.getElementById("First");
div1.addEventListener("click", function (e) {
if (event.currentTarget.classList.contains('active')) {
event.currentTarget.classList.remove('active');
var element = document.getElementById("Second");
element.classList.add("active");
} else {
event.currentTarget.classList.add('active');
var element = document.getElementById("Second");
element.classList.remove("active");
}
});
var div2 = document.getElementById("Second");
div2.addEventListener("click", function (e) {
if (event.currentTarget.classList.contains('active')) {
event.currentTarget.classList.remove('active');
var element = document.getElementById("First");
element.classList.add("active");
} else {
event.currentTarget.classList.add('active');
var element = document.getElementById("First");
element.classList.remove("active");
}
});
.active{
color:red;
}
<div id"newNav">
<a class="navbar-item te" id="First" href="#Delivery">
<span class="icon"><i class="fas fa-shipping-fast"></i></span>
<span>Delivery</span>
</a>
<li class="navbar-item" id="Second">
<span>Delivery2</span>
</li>
</div>
Use document.querySelectorAll()
The Document method querySelectorAll() returns a static (not live)
NodeList representing a list of the document's elements that match the
specified group of selectors.
document.querySelectorAll('nav.navbar-item')
.forEach((node) => node.className += ' current')
Here, nav.navbar-item is the selection required, and current is the new class to be appended to the nodes selected by querySelector.
Adding verbose solution:
let classToBeAdded = 'current';//new class to be added
let myNavs = document.querySelectorAll('nav.navbar-item');//Selects all navs with the given class
for(let element of myNavs) {//looping through the elements captured by the above query
element.classList.add(classToBeAdded);//Appending new class to the element
}
Related
I have this code that will console.log the innerHTML of the list element that is clicked, it works perfectly
But I wanted to only console.log the innerHTML of the span element with class "x" that is inside the list
how can I do this?
function myfunction() {
let items = document.querySelectorAll("#ol li"),
array = [];
for (var i = 0; i < items.length; i++) {
array.push(items[i].innerHTML);
}
for (var i = 0; i < items.length; i++) {
items[i].onclick = function() {
console.log(this.innerHTML)
}
};
}
<ol id="ol">
<li>
<span class="x">hello</span>
<span class="xx">testing</span>
</li>
<li>
<span class="x">hello2</span>
<span class="xx">testing2</span>
</li>
<li>
<span class="x">hello3</span>
<span class="xx">testing4</span>
</li>
<li>
<span class="x">hello4</span>
<span class="xx">testing4</span>
</li>
</ol>
<button onclick="myfunction()">click</button>
Rather than placing a listener on each li, you can take advantage of event delegation, placing a single handler on the ol:
<ol id="ol">
<li>
<span class="x">hello</span>
<span class="xx">testing</span>
</li>
<li>
<span class="x">hello2</span>
<span class="xx">testing2</span>
</li>
<li>
<span class="x">hello3</span>
<span class="xx">testing4</span>
</li>
<li>
<span class="x">hello4</span>
<span class="xx">testing4</span>
</li>
</ol>
<button id="button">click</button>
'use strict';
const button = document.querySelector('#button');
const findLI = el => {
if (el.tagName.toLowerCase() === 'li') {
return el;
}
return findLI(el.parentElement);
};
const registerItemsClickHandler = () => {
const ol = document.querySelector('#ol');
ol.onclick = event => {
const li = findLI(event.target);
console.log(li.innerHTML);
};
};
button.onclick = registerItemsClickHandler;
Notice that we only register a single click handler (on the ol) and that we can use event.target to determine the specific element onto which the event was dispatched. It's also worth noting that a child any depth of the tree can be a dispatch target, so we can use the recursive findLI() function to find the first parent that is an li, if el itself isn't one.
I need to remove and add a class between elements of a list, if I hit the #swapThumb button it should remove the selected class from the current element and then added to the next element.
Here's what I have
html
<ul id="product-thumbnails" class="thumbnails list-inline">
<li class="vtmb vt-123 selected" style="">
<img src="https://via.placeholder.com/100x100">
</li>
<li class="vtmb vt-456" style="">
<img src="https://via.placeholder.com/100x100">
</li>
<li class="vtmb vt-789" style="display: none">
<img src="https://via.placeholder.com/100x100">
</li>
<li class="vtmb vt-101" style="">
<img src="https://via.placeholder.com/100x100">
</li>
<li class="vtmb vt-121" style="display: none">
<img src="https://via.placeholder.com/100x100">
</li>
</ul>
<button id="swapThumb">Next</button>
javascript
let thumbsNailsList = $('#product-thumbnails').find('li');
let swapButton = $('#swapThumb');
thumbsNailsList.each((index, item) => {
let thumbsAvailable = $(item).attr('style');
if (thumbsAvailable === '') {
$(swapButton).on('click', () => {
$(item).removeClass('selected');
$(item).closest($(item)).next().addClass('selected');
});
}
});
First I'm checking if the li element has an empty style attribute (this is needed), if so, trigger the click validation.
The click should remove the selected class from the first element and then added to the next one and so on (it should match the empty style attribute). Once the selected class hits the last element of the list it should return the class to the first element.
This code snippet will change the class of the element beneath it to selected and remove it from the current one, while keeping all the other classes. It will also loop back to the beginning element if next is clicked when on the last element. I've heard jQuery functions are more expensive that document functions and shouldn't be used for these kinds of things. Apply this to your problem and you should get the expected result
let i = 0;
let thumbsNailsList = document.getElementById("product-thumbnails").children;
let btn = document.getElementById("btn");
btn.onclick = function() {
var prevClasses = thumbsNailsList[i].className;
thumbsNailsList[i].className = prevClasses.replace("selected", "");
i = (i+1) % thumbsNailsList.length;
thumbsNailsList[i].className = "selected";
console.log(thumbsNailsList);
}
<ul id="product-thumbnails">
<li class='selected'></li>
<li class=''></li>
<li class=''></li>
<li class=''></li>
</ul>
<button id="btn">Next</button>
I want to get the ancetor of the li that have active class to target his son (the button) class an make a collapse by area-expanded= true in it.
This is the html:
<li class="nav-item">
<button class="nav-link" type="button" data-toggle="collapse" data-target="#nav-collapse-2" aria-controls="nav-collapse-2" aria-expanded="true">Typographies</button>
<div class="nav-collapse collapse show" id="nav-collapse-2" style="">
<div class="nav-collapse-inner">
<ul class="nav-submenu">
<li class="nav-submenu-item">
<a class="nav-submenu-link active" href="sg-typo-familles.html">Les familles</a>
</li>
<li class="nav-submenu-item">
<a class="nav-submenu-link" href="sg-typo-hierarchisation.html">Hiérarchisation</a>
</li>
</ul>
</div>
</div>
</li>
this is some js :
var get_url = function (){
$(".navbar-nav--left .nav-link, .nav-submenu .nav-submenu-link").each(function(){
var $this = $(this);
if($this.attr('href') == window.location.href.substr(window.location.href.lastIndexOf('/') + 1)){
// var regex = /\/\/.*\/(.*)\//g;
// var match = regex.exec(window.location.href);
// console.log("eeeeeee : ",match )
$this.addClass('active');
// var collapsed = $(".nav-item *");
collapsed = $(this).closest(".nav-item")[0];
}
});
};
I'm stuck in this piece of code :(
I didn't understand well your question, but in order to get the parentElement of an element with a class .active here is how:
let myElement = document.getElementByClassName("active")[0];
let brotherButton = myElement.parentNode.querySelectorAll("a")[0];
Above we've got myElement which has the class .active, then thru his parent we selected his brother anchor tag.
Hope this help.
I need to disable, deactivate or at least hide a dropdown item called Private request and I can only use CSS or Javascript to do so.
When I inspect the dropdown item it has the class a.js-dropdown-list. But every item in my dropdown has this class. So I can't just use {display: none;} because it will hide all options. Is there no more specific ID for every item in the drop down or can I deactivate items with Javascript?
Drop Down looks like this:
Here the code (1st block is for the picker field, 2nd for the drop-down menue):
<div id="js-organization-picker">
<sd-select class="js-share-with-organisation-picker is-private" data-type="link" data-id="customfield_10203" data-value="38" data-options="[{"label":"Private request","styleClass":"is-private","icon":"locked"},{"label":"Share with Testorganisation","value":38,"icon":"unlocked"}]" resolved="">
<a id="js-customfield_10203-dropdown-trigger" class="aui-dropdown2-trigger aui-button aui-button-link js-trigger customfield_10203-trigger select-dropdown-trigger aui-alignment-target aui-alignment-element-attached-top aui-alignment-element-attached-left aui-alignment-target-attached-bottom aui-alignment-target-attached-left active aui-dropdown2-active aui-alignment-enabled" aria-controls="customfield_10203-dropdown" aria-haspopup="true" role="button" tabindex="0" data-aui-trigger="" data-dropdown2-hide-location="js-customfield_10203-dropdown-container" resolved="" aria-expanded="true" href="#customfield_10203-dropdown">
<span class="aui-icon aui-icon-small aui-iconfont-locked">
: : before
</span> Private request
: : after
</a>
<input name="customfield_10203" type="hidden" class="js-input" value="">
<div id="js-customfield_10203-dropdown-container" class="hidden"></div>
</sd-select>
</div>
<div id="customfield_10203-dropdown" class="aui-dropdown2 filter-dropdown aui-style-default js-filter-dropdown select-dropdown aui-layer aui-alignment-element aui-alignment-side-bottom aui-alignment-snap-left aui-alignment-element-attached-top aui-alignment-element-attached-left aui-alignment-target-attached-bottom aui-alignment-target-attached-left aui-alignment-enabled" role="menu" aria-hidden="false" data-id="customfield_10203" resolved="" style="z-index: 3000; top: 0px; left: 0px; position: absolute; transform: translateX(602px) translateY(918px) translateZ(0px);" data-aui-alignment="bottom auto" data-aui-alignment-static="true">
<div role="application">
<ul class="aui-list">
<li>
<a class="js-dropdown-item " href="#">Private request</a>
</li>
<li></li>
<li>
<a class="js-dropdown-item " href="#" data-value="38">Share with Testorganisation</a>
</li>
<li></li>
</ul>
</div>
</div>
E.g. you could give the dropdown item ids to identify them. In HTML this would look like this: <p id="yourIdHere"></p>
You can access this item through Javascript using the document.getElementById() function like this: document.getElementById('yourIdHere').style.display = 'none';
If you can't edit the existing html code, youi have to get the element by it's name/value. This is a bit difficult. You have to iterate through all elements of that type and evaluate each name/value. If you have found the one, you was looking for, you can edit/hide it. You would do so (untested):
var elements = document.getElementsByTagName('div'); //div will be the name of the tag of your elements in the dropdown list
var length = elements.length;
for (var i=0, item; item = elements[i]; i++) {
if(item.value == "Private request") { //"Private request" is the name of the element we are looking for
item.style.display = 'none'; //Hide the element
}
}
You could loot trough all 'js-dropdown-items', check its innerText for 'Private request' and set its parentNodes display-property to 'none':
var list = document.getElementsByClassName('js-dropdown-item');
for(var i = 0; i < list.length; i++){
if(list[i].innerText === 'Private request') list[i].parentNode.style.display = 'none';
}
<ul class="aui-list">
<li>
<a class="js-dropdown-item " href="#">Private request</a>
</li>
<li></li>
<li>
<a class="js-dropdown-item " href="#" data-value="38">Share with Testorganisation</a>
</li>
<li></li>
</ul>
VannillaJS Solution document.querySelectorAll(".aui-list > li")[0].style.display = "none";
Welcome!
If I get you right there are plenty of elements with the same ID js-dropdown-list and you want to hide a specific one and there is no additional class for the element and you're not allowed to add specificity to it, let's say by adding of an additional class, you can do the following:
Grab all elements with this id by:
let elements = document.querySelectorAll('.js-dropdown-list'); // this is an array of these elements
let elementToHide = elements[n] // whene n is the number of that element
//hiding the element
elementToHide.style.display = 'none';
Hope that helps!
NOTE: I believe you will have to actually hide it OR use whatever you are using for this pseudo drop down (there was no reference in the question) to manage the disabled state if it provides that. Reference: https://www.w3.org/TR/2014/REC-html5-20141028/disabled-elements.html
Get the element by its text and then hide it. Might need the parent but this directly answers the question. Note this could all be wrapped in a function and then called from where you wish.
function HideByText(elId, findText) {
let group = document.getElementById(elId).getElementsByClassName('js-dropdown-item');
let found = Array.prototype.filter.call(group, function(el) {
return el.innerText === findText;
});
found.forEach(function(el) {
el.style.display = 'none';
});
return found;// in case you need the elements ref.
}
let foundFiltered = HideByText('customfield_10203-dropdown', 'Private request');
<div id="customfield_10203-dropdown" class="aui-dropdown2 filter-dropdown aui-style-default js-filter-dropdown select-dropdown aui-layer aui-alignment-element aui-alignment-side-bottom aui-alignment-snap-left aui-alignment-element-attached-top aui-alignment-element-attached-left aui-alignment-target-attached-bottom aui-alignment-target-attached-left aui-alignment-enabled"
role="menu" aria-hidden="false" data-id="customfield_10203" resolved="" data-aui-alignment="bottom auto" data-aui-alignment-static="true">
<div role="application">
<ul class="aui-list">
<li>
<a class="js-dropdown-item " href="#">Private request</a>
</li>
<li></li>
<li>
<a class="js-dropdown-item " href="#" data-value="38">Share with Testorganisation</a>
</li>
<li></li>
</ul>
</div>
</div>
Alternate for parent would be:
Change el.style.display = 'none'; to
if (node.parentElement) {
el.parentElement.style.display = 'none';
}
Have you tried using CSS? Not an ideal solution, but it might be better than using JS for this.
#js-organization-picker + .aui-dropdown2 .aui-list li:first-child {
display: none;
}
If you need to hide the first 2 elements, you could do something like:
#js-organization-picker + .aui-dropdown2 .aui-list li:first-child,
#js-organization-picker + .aui-dropdown2 .aui-list li:first-child + li {
display: none;
}
This question already has answers here:
How to remove the class in javascript?
(3 answers)
Closed 9 years ago.
I have a div section
<div class="1">
<div id="tab1"">
<ul class="nav nav-tabs">
<li class="active ans-tab"> MyText</li>
<li class="topTab">Game</li>
<li class="topTab">LB</li>
</ul>
</div>
<div id="tab2">
<ul class="nav nav-pills">
<li class="active"> Top</li>
<li>Categories</li>
</ul>
</div>
</div>
What i am trying to do at each of the pages used as href in the div, is to remove class attribute from the li item which has it as active and assign it to the one, i click.
I have tried removeClass removeAttribute etc but nothing seems to be working for me. I want to use plain Javascript no jQuery
For e.g. my JS code on Game page removes active class from MyText page and add it to Game page's li element.
I assume only one is active at a time. To remove, you can do this:
var active = document.querySelector(".active");
active.classList.remove("active");
Then to add, do this:
// Assuming `this` is your element
this.classList.add("active");
Both of these will work in modern browsers. For older browsers, use the same DOM selection, then do typical string manipulation of the .className property.
active.className = active.className.replace(/\bactive\b/, " ");
this.className += " active";
Like this
.bold {
font-weight: bold
}
.red {
background: red
}
<div id="theDiv" class="bold red">Bold and red</div>
<button id="button">Remove red</button>
var theDiv = document.getElementById("theDiv");
var button = document.getElementById("button");
function removeRed() {
var classContent = theDiv.className;
theDiv.className = classContent.replace("red", "").trim();
}
button.addEventListener("click", removeRed, false);
on jsfiddle
On newer browsers you can use element.classList and the remove method
Try function for removing a class:
function removeClass (parentEl, classToBeRemoved) { // DOM element, className for remove.
var classes = parentEl.className.split(" ");
for (var i = 0; i < classes.length; i++) {
if (classes[i] == classToBeRemoved) {
// Remove class.
classes.splice(i, 1);
}
break;
}
parentEl.className = classes.join(" ");
}