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(" ");
}
Related
I have to loop through a ol and then get each of the li and then remove the text and add "<a" element to it.
Following is the html that is rendered:
<ol class="progress">
<li class="list-group-item text-muted list-group-item-success active">
General Information<span>1</span>
</li>
</ol>
I want to remove all the classes except "active" and then wrap the text with General Information
Like below
<ol class="progress">
<li class="active">
General Information<span> 1</span>
</li>
</ol>
I have tried to loop through the Ol using the script below but it seems to not find anything
$('ol.progress').each(function (i, li) {
var listItem = li;
var lm = $(li).text();
console.log(lm);
});
I see you are using JQuery - so let's stick to this.
You are looping over the ol but you want to loop over the ol's lis.
So replace
$('ol.progress').each....
by
$('ol.progress li').each....
You can remove all classes with the .removeClass() without any parameters.
But as you want to preserve the active-class you have to preserve this attribute - in my version of the code (see below) I will use a variable for this.
In addition you want to replace the HTML-part and not the text-part - so your snippet would read
$('ol.progress li').each(function () {
var is_active = false;
is_active = $(this).hasClass('active');
$(this).removeClass();
if(is_active){
$(this).addClass('active');
}
var newcontent = '' + $(this).html() + "";
$(this).html(newcontent);
});
With vanilla js:
document
.querySelectorAll('ol.progress > *') // all children of <ol> with class .progress
.foreach(elem => {
elem.className = 'active'
elem.innerHTML = `${elem.innerHTML}`
})
With jquery, as you can see, I check if the element has a class, then I remove all the classes and add active if it had it.
$('ol.progress li').each(function(i, li) {
var listItem = li;
if ($(li).hasClass('active')) {
$(li).removeAttr('class');
$(li).addClass('active');
} else {
$(li).removeAttr('class');
}
});
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="progress">
<li class="list-group-item text-muted list-group-item-success active">
General Information<span>1</span>
</li>
<li class="list-group-item text-muted list-group-item-success">
General Information<span>2</span>
</li>
<li class="list-group-item text-muted list-group-item-success">
General Information<span>3</span>
</li>
</ol>
In your code you forgot li into selector so $('ol.progress li') instead of $('ol.progress')
In my project, there are so many jQuery toggles needed for changing text and icons. Now I’m doing that using:
$("#id1").click(function () {
//Code to toggle display and change icon and text
});
$("#id2").click(function () {
//Same Code to toggle display and change icon and text as above except change in id
});
The problem is that I got so many to toggle, the code is quite long but all I change for each one is the id. So I was wondering if there is any way to make this simple.
Below is a sample pic. I got so many more in single page.
There are two issues here.
How to run the same action on multiple elements
How to know which element you've clicked so that you can run a relevant action on it. (most of the existing answers skip this part).
The first is to use a class for each of the elements you want to click, rather than wire up via an id. You can use a selector similar to [id^=id] but it's just cleaner to use a class.
<div id="id1" class="toggler">...
which allows you to:
$(".toggler").click(function() ...
the second is it associate the clickable with the item you want to toggle. There are many ways to do this, my preferred option is to associate them with data- attributes, eg:
<div class="togger" data-toggle="#toggle1">...
which allows you to:
$(".toggler").click(function() {
$($(this).data("toggle")).toggle();
});
The key here is that this is the element being clicked, so you can do anything else with this such as show/hide an icon inside or change colour.
Example:
$(".toggler").click(function() {
$($(this).data("toggle")).toggle();
$(this).toggleClass("toggled");
});
.toggler { cursor: pointer }
.toggled { background-color: green }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggler" data-toggle="#t1">T1</div>
<div class="toggler" data-toggle="#t2">T2</div>
<div class="toggler" data-toggle="#t3">T3</div>
<hr/>
<div id="t1" style='display:none;'>T1 content</div>
<div id="t2" style='display:none;'>T2 content</div>
<div id="t3" style='display:none;'>T3 content</div>
Oh,Can you use a class instead of id?
<ul>
<li class="idx">A</li>
<li class="idx">B</li>
<li class="idx">C</li>
</ul>
$(".idx").click(function(e){
//Code to toggle display and change icon and text
let target = e.target;
//You can do all what you want just base on the `target`;
});
You can store the queries in an array, and iterate over them to perform the same JQuery operation on all of them
let ids = ["#id1", "#id2", "#id3", "#randomID"]
ids.forEach((id) => {
console.log($(id).html())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="id1">A</li>
<li id="id2">B</li>
<li id="id3">C</li>
<li id="randomID">D</li>
</ul>
Or (If like your example) and all of the id's are actually id1, id2, id3, ... etc.
let id = "id";
let n = 3; //amount of id's
for (let i = 1; i <= n; i++) {
console.log($("#" + id + i).html())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="id1">A</li>
<li id="id2">B</li>
<li id="id3">C</li>
</ul>
You can try the below code.
var num = $("#myList").find("li").length;
console.log(num)
for(i=0;i<num;i++){
$("#id"+ i).click(function(e){
let target = e.target;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ul id="myList">
<li id="id1">A</li>
<li id="id2">B</li>
<li id="id3">C</li>
</ul>
This question already has answers here:
How do I retrieve an HTML element's actual width and height?
(16 answers)
Closed 3 years ago.
Initially have 5 buttons in div, and i have a code to create buttons dynamically see the code below..
My main question is after adding some more buttons. I have top and down arrow buttons to scroll the div.
I want to scroll one button or (set of buttons) on each click.
On each click now i am getting some portion of the button.
How can i get full button on each click with out considering how much width that dynamically created button have
This is my Html code snippet
<div class="tabbar-fix" style="width: 11.2%;height: 89%;position: fixed;">
<div class=" row" style="height:5%;width:100%">
<div id="top-button" class="scroller" onclick="scrollLeftAbc();"><i class="glyphicon glyphicon-chevron-up"></i></a></div>
</div>
<div class="row" style="height:90%;width:100%;">
<nav class="navbar navbar-inverse" id="nav-id-scroll">
<ul class="nav navbar-nav" id="navbar-buttons">
<li class="active">Home</li>
<li>about</li>
<li>services</li>
<li>contact</li>
<li>contact</li>
<li>services</li>
</ul>
</nav>
</div>
<div id="down-button" class="row" style="height:5%;width:100%">
<div class="scroller" onclick="scrollRightAbc();"><i class="glyphicon glyphicon-chevron-down"></i></a></div>
</div>
</div>
My function to create dynamic button.....
function createButton() {
var ul = document.getElementById("navbar-buttons");
var li = document.createElement("li");
var link = document.createElement("a");
var name = document.getElementById("recipient-name").value;
link.setAttribute("href", name);
link.setAttribute("data-toggle", "tab");
var textName = document.createTextNode(name);
link.appendChild(textName);
li.appendChild(link);
ul.appendChild(li);
// $(li).insertBefore("#lastIcon");
}
This is how i tried to scroll the button onclick ..
var test = 0;
function scrollToLeft() {
test = document.querySelector("li").offsetWidth;
console.log(test)
document.getElementById('nav-id-scroll').scrollLeft += test;
}
function scrollToRight() {
document.getElementById('nav-id-scroll').scrollLeft -= test;
}
Let's assume you want to measure the width of last li or button (whatever you add), so here goes the code for same.
var button_width = $('#navbar-buttons > li:last-of-type').width();
Now, you may play with the value of button_width. Or you may use $.each to calculate the width of all buttons individually into an array.
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;
}
I am still learning to do plain old vanilla javascript. I am trying to hide my slideToggle or even the whole background of the drop down menu I did to close when user clicks on the any link. Am I missing something because I am not getting any error but it doesn't display none on the slideToggle class.
js
var anchors = document.querySelectorAll(".a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].addEventListener('click', function(e){
var btn = document.querySelector(".slideToggle");
if (window.getComputedStyle(btn,null).getPropertyValue("display") != 'none') {
btn.click();
}
})
}
html
<nav id="mainNav">
<h1 class="hidden">Main Navigation</h1>
<button id="button"><span class="hidden">Toggle</span></button>
<ul id="burgerMenu">
<li>Home</li>
<li>Latest Work</li>
<li>About</li>
<li>Prices</li>
<li>Contact</li>
</ul>
</nav>
instead of using document.querySelectorAll(".a") use document.querySelectorAll("a"). also I don't see an element with slideToggle as a class. using a "." as a selector means you are searching for a class.