I have the following....
<div class="validationbox">
<h1>Errors</h1>
<ul class="validationerrors">
<li>Error 1</li>
<li>Error 2</li>
<li>Error 3</li>
</ul>
</div>
The error list items are generated dynamically so sometimes there are none, I would like to hide the 'validationbox' div if there are no list items.
I imagine it is javascript or jquery that I should be looking at, does anyone have any examples?
In jQuery you can do it as simple as:
$(".validationbox:not(:has(li))").hide();
In pure JavaScript you need to iterate ".validationbox" elements and search for <li> nodes inside:
var div = document.getElementsByClassName("validationbox");
for (var i = 0, len = div.length; i < len; i++) {
if (!div[i].getElementsByTagName("li").length) {
div[i].style.display = "none";
}
}
$('.validationbox').toggle( $('.validationerrors li').length );
toggle() accepts a boolean value as an argument. $('.validationerrors li').length will evaluate to false if there is no <li> elements, else true, which will show the error list.
you can use not .
$('div .validationbox').not(':has(li)').hide();
hope it's help to you
Related
I am using javascrypt with selenium. I need to search and select one of the items in this list, but I am unable to select it. I can find it, but not select the element.
Please help me, thank you very much
var input = document.evaluate("//li[contains(., 'ATACAMA')]", document, null, XPathResult.ANY_TYPE, null );
var thisregion = input.iterateNext();
thisregion.click();
You could try the following below:
var input = document.evaluate("//li[text()='ATACAMA']", document, null, XPathResult.ANY_TYPE, null );
var thisregion = input.iterateNext();
thisregion.click();
So I don't have a clue about Xpath, but like you said, there is nothing stopping you from using querySelector or in this case querySelectorAll instead.
Here I create an array of all the li elements and use .find to get the element that has the text "Item 3" in it. I then click the element programmatically. All of the li elements have onClick event inline in the html.
Would this work for you?
let li_item = Array.from(document.querySelectorAll('li'))
.find(x => x.textContent === 'Item 3');
li_item.click();
function select(element, n) {
element.style.color = "red";
console.log(`${n} has been selected!`);
}
<ul>
<li onClick = "select(this, 1)">Item 1</li>
<li onClick = "select(this, 2)">Item 2</li>
<li onClick = "select(this, 3)">Item 3</li>
<li onClick = "select(this, 4)">Item 4</li>
<li onClick = "select(this, 5)">Item 5</li>
</ul>
I'm trying to move all the list items from an list to another using only javascript but for some reason only half of them are actually moved.
Heres a working example of what I'm doing:
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
for (var x = 0; x < stores_li.length; x++) {
document.getElementById('hide').appendChild(stores_li[x]);
stores_li[x].className += ' teste';
}
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
What seems to be the problem?
getElementsByClassName returns a live list.
When you append the element to a different element, you change its position in the list.
So it starts off as:
1 2 3 4
Then you move the first one:
2 3 4 1
Then you access the second one … but the second one is now 3 because everything has shuffled down the list.
You could copy each element into an array (which will not be a live list) and then iterate over that array to move them (so they won't change positions as you go).
Alternatively, you could use querySelectorAll which returns a non-live list.
You should better use querySelectorAll than getElementsByClassName
var results_ul = document.getElementById('results');
var stores_li = document.querySelectorAll('.store-list-item');
stores_li.forEach((item)=>{
document.getElementById('hide').appendChild(item);
item.className += ' teste';
});
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
Try use querySelectorAll . It'll returns a non-live list. That's what you need.
var stores_li = document.querySelectorAll('.store-list-item');
To increase more information:
Live : when the changes in the DOM are reflected in the collection. The content suffers the change when a node is modified.
Non-Live : when any change in the DOM does not affect the content of the collection.
document.getElementsByClassName() is an HTMLCollection, and is live.
document.querySelectorAll() is a NodeList and is not live.
In your code you are removing each element from the first list and inserting into the new list. After you remove 2 elements it will have only 2 elements in the first list but now you are searching the 3 rd index in the loop which is not there. So to make it work i have prepended each element from the last.
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
var hide_ul = document.getElementById('hide');
for (var x = 0, y = stores_li.length; x < y; x++) {
hide_ul.insertBefore(stores_li[y-x-1],hide_ul.firstChild);
stores_li[x].className += ' teste';
}
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
Or you may want to clone the element with Jquery and you can push into the clonned ones then delete the orginals from top. I could not find any equivalent of clone() for js but if you want to check link is here
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
while(stores_li.length>0) {
document.getElementById('hide').appendChild(stores_li[0]);
stores_li[x].className += ' teste';
}
I have an array and I want to be able to divide it in 2 components, so like the first 5 elements go in one element and whatever is left go in the second element. I know I have to use slice and I can get the first component but not sure about the second one.
I have something like this:
if (item.children) {
return item.children.slice(0, 5).map((childItem) => {
const navItem = (
<Link activeClassName={styles.active} to={childItem.url}>{childItem.text}</Link>
)
return (
<li key={childItem.id}>
{navItem}
</li>
)
})
}
So how do I get another component to appear after, like
<li key={childItem.id}>
{navItem}
</li>
{navExtra}
that contains all the remaining elements from the array?
The final html should look something like this:
<ul>
<!-- // first five elements of the array -->
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<!-- // new component -->
<li>
<button>Extra</button>
<ul>
<!-- // remaning elements of the array -->
<li>Item 6</li>
<li>Item 7</li>
<!-- // etc -->
</ul>
</li>
</ul>
Variables will really help your code readability here. slice(beginIndex, endIndex) and slice(begin) are the keys.
You already know slice(0,5) will get you the first half of the array.
var x = slice(5) will get you the components of the array from the fifth element to the end. You can call map() and do any other processing on these elements to get something to display.
MSDN docs for slice
You can create an HTML element with appendChild. Here is an example of how you could do what you are trying to do:
<!DOCTYPE html>
<html>
<body>
<div id="div1">
</div>
<script>
var array = ["this", "is", "a", "random", "array", "that", "i", "just", "made"];
var splitBy = Math.round(array.length / 2);
//for first half
for (var i = 0; i <= splitBy; i++){
var li = document.createElement("li");
var node = document.createTextNode(array[i]);
li.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(li);
}
//for second half
for (var i = splitBy + 1; i < array.length; i++){
var li = document.createElement("li");
var node = document.createTextNode(array[i]);
li.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(li);
}
</script>
</body>
</html>
Hope this helps!
When you use splice, it alters the original array, essentially leaving you item.children with all of the elements you want to include in navExtra
We can create a return object that holds navItems and navExtra separately for you to render separately, adding the wrapping <ul> in the render, etc.
if (item.children) {
let ret = {
navItems: [],
navExtra: []
};
navItems = item.children.splice(0, 5);
ret.navItems.push(
navItems.map(navItem => {
return (
<li key={navItem.id}>
<Link activeClassName={styles.active} to={navItem.url}>{navItem.text}</Link>
</li>
)
})
)
ret.navExtra.push(
item.children.map(navExtra => {
<li key={navExtra.id}>
<Link activeClassName={styles.active} to={navExtra.url}>{navExtra.text}</Link>
</li>
})
)
}
I'm looking for a way to add a class to a certain element with another class.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li class="hide">Item 4</li>
<li class="hide">Item 5</li>
<ul>
JS/Jquery
if($('li').hasClass('hide')) {
$('li').removeClass('hide').addClass('slide-down');
}
The problem is that the class slide-down gets added to all li elements.
Is there a way to only target the li elements that have the hide class removed?
Mh maybe it's due to the typo in your HTML: class"hide" (you are missing the equal sign).
Also you got a logical error in your code:
if($('li').hasClass('hide')) the condition will yield true if any <li> element in your document has the hide class.
$('li').removeClass('hide').addClass('slide-down'); the first segment $('li') will actually select ALL <li> elements in your document and remove the class hide from them and add the slide-down to ALL <li> elements in your document.
Here's how I'd do it:
$('li.hide').removeClass('hide').addClass('slide-down');
Note that jQuery is about chaining, i.e selecting subsets and applying functions to these subsets.
What this line does is:
$('li.hide') selects all <li> elements in your document which have the hide class - this becomse your "working subset" now.
.removeClass('hide') removes the hide class from this subset we got in the first step and returns the same subset again.
.addClass('slide-down') adds the slide-down class to all <li> in the selected subset returned from step 2, which is the same as from step 1.
JS fiddle: https://jsfiddle.net/q0nzaa7t/
In vanilla JS:
var liHide = document.querySelectorAll('li.hide');
var i;
var length = liHide.length;
for (i=0;i<length;i++) {
liHide[i].className = 'slide-down';
}
Note that, for some reason, querySelectorAll doesn't get updated automatically like document.getElementsByClassName. The same code wouldn't work if we would have used that method for querying the DOM:
var liHide = document.getElementsByClassName('hide');
var i;
var length = liHide.length;
for (i=0;i<length;i++) {
liHide[i].className = 'slide-down'; //<-- this won't update the 2nd element
}
This would have only changed the first element, since liHide[1] becomes liHide[0], because <li class="hide">Item 4</li> is no longer part of HTML Collection.
Plain javascript for the ones with querySelectorAll and classList support:
var items = document.querySelectorAll('li.hide');
for (var i = 0; i < items.length; i++) {
items[i].classList.remove('hide');
items[i].classList.add('slide-down');
}
Without querySelectorAll:
var items = document.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
if (items[i].classList.contains('hide')) {
items[i].classList.remove('hide');
items[i].classList.add('slide-down');
}
}
Without querySelectorAll and classList:
var items = document.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
if (new RegExp(/(?:^|\s)hide(?!\S)/g).test(items[i].className)) {
items[i].className = items[i].className.replace(/(?:^|\s)hide(?!\S)/g , '');
items[i].className += ' ' + 'slide-down';
}
}
There are <li> elements that one of them has class="current". I want to decide which of <li> is current. Here is view:
#{
int k = 10; //this will change in every request
}
<ul class="car">
#foreach (var item in modelCount)
{
<li
#{if (item.Id == k) { <text>class="current"</text>} }>
#item.Name
</li>
}
</ul>
This works, but the first <li> is always current by default. When first element is current by my expression, everything is ok, but otherwise, <ul> has 2 current <li>.
How can I solve this problem with jquery function?
Edit:
I need:
If <li> elements have 2 current classes, to remove the first of them.
function removeDuplicateCurrentClass(){
var currentListElements = [];
$('ul.car li').each(function(){
if($(this).hasClass('current'))
currentListElements.push(this);
});
if(currentListElements.length > 1)
$(currentListElements[0]).removeClass('current');
//if more than one current class exist: remove the first one
}
$(function(){
removeDuplicateCurrentClass();
//or simply
if($('ul.car li.current').length > 1)
$('ul.car li.current:first').removeClass('current');
});