Javascript If List Element contains 'Whatever', don't display - javascript

I've got some code in html like
<li id="1"></li>
<li id="2">Whatever</li>
<li id="3"></li>
Is there any way I can make it so that if the li contains a piece of text, it won't be displayed, yet all the other lis will be unaffected?

You could loop through your lis and use document.getElementById(id).innerHTML to get the value inside it to compare to, and if so, use document.getElementById(id).style.display = 'none';

var list = document.getElementsByTagName("li");
for(var i = 0; i < list.length; i++){
if(list[i].textContent === "Whatever"){
list[i].style.display = "none";
}
}
Live Demo

Here's a couple of examples using exact/non-exact matches, case-sensitive and insensitive.
http://jsfiddle.net/ZgrzL/
Edit: wow, I'm slow.

Related

How can i replace HTML tag to another in javascript

I am new with js and playing with replace method.
I have had no problems when replacing string for another string etc., but when im trying to do same with tags nothing happens..
Im trying to replace every tags for -tags. My function is below:
function bonus() {
var list = document.getElementsByTagName('li');
for (var i = 0; i < list.length; i++) {
newList = document.getElementsByTagName('li')[i].innerHTML;
newList = newList.replace('<li>', '<strong>');
newList = newList.replace('</li>', '</strong>');
document.getElementsByTagName('li')[i].innerHTML = (newList);
//console.log(newList);
}
}
function bonus(){
var list=document.getElementsByTagName('li');
var len = list.length;
for(var i=len-1; i>-1; i--){
var tmpItem = list[i]
newList = tmpItem.outerHTML;
newList = newList.replace('<li>','<strong>');
newList = newList.replace('</li>','</strong>');
tmpItem.outerHTML = newList;
}
}
I thought you might change your code like above, and there was still much space to optimize your code. go ahead <( ̄︶ ̄)>
First of all you should never replace a list-item with another element like that. A list item must always be a child of an ul or ol elelment, and ul and ol elements should not have any other immediate child that isn't a li.
However, this doesn't work because the li is an html element and not a text string and the inner HTML of an html elemnt doesn't contain the tag itself. It may contain children and those children's tags are part of the innerHTML, everything inside the element/tag itself is the innerHTML.
An example to clarify:
<ul>
<li>one<strong>second one</strong></li>
<li>two<strong>second two</strong></li>
<li>three<strong>second three</strong></li>
<li>four</li>
</ul>
Looping through all list items accessing elements as you've describe
for(var i=0; i<list.length;i++) {
console.log("==>> " + document.getElementsByTagName("li")[i].innerHTML);
}
Will output the following to the console:
==>> one<strong>second one</strong>
==>> two<strong>second two</strong>
==>> three<strong>second three</strong>
==>> four
If you want to make all li elements strong they should be nested as this:
<li><strong>Some text</strong></li>
To Achieve this one way to do it would be:
var list = document.getElementsByTagName("li");
for(var i=0; i<list.length; i++) {
var listItem = list[i];
listItem.innerHTML = "<strong>" + listItem.innerHTML + "</strong>";
}
If you want to convert all li elements to strong elements you must first remove them from the list...
Thanks alot for all of you. I knew that i can't change li for strong in real world, but i just tried to figure out if its possible to do so with simple loop.
My example html is full of lists, so thats why i used li instead of h2 to h3 or something like that. Outer html was new thing for me, and solution for this one. However Kim Annikas answer helped me with other question about modifying lists: I did this:
function replace(){
var list=document.getElementsByTagName('li');
for(var i=0;i<list.length;i++){
newText="<strong>Replaced!</strong>";
var listItem=list[i];
listItem.style.color="red";
listItem.innerHTML=newText;
}
}
..and now it seems that i have learnt how to modify tags as well as text inside of it ;)

Can't change style : display using getelementbyclassname

document.getElementByClassName('xyz').style.display = 'none';
I am unable to hide class content.
document.getElementsByClassName return an array like object. you can use following script for this
document.getElementsByClassName('xyz')[0].style.display = 'none';
or if you want to hide all .xyz element
var x = document.getElementsByClassName("xyz");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = 'none';
}
function show(){
var element = document.getElementsByClassName('elem');
console.log(element);
element[0].style.display = 'block';
}
.elem {
display: none;
}
<div> visible
<div class="elem">hidden
</div>
<button type="button" onclick="show()">click</button>
</div>
getElementsByClassName returns an array, you can't directly set the style of element like it.
You need to do something like:
let elem = document.getElementsByClassName('xyz')[0];
elem.style.display = 'none';
document.getElementsByClassName elements is a live HTMLCollection of found elements.
<div class="xyz">
test content
</div>
<button type="button" onclick="document.getElementsByClassName('xyz')[0].style.display = 'none';">Hide Content </button>
<button type="button" onclick="document.getElementsByClassName('xyz')[0].style.display = '';">Show Content </button>
$("#afficher_commentaire").change(function(){
// alert("OK");
if($(this).prop("checked") == true){
var commentaire_date_fin_fourniture = document.getElementsByClassName("commentaire_date_fin_fourniture");
for (var i = 0; i < commentaire_date_fin_fourniture.length; i++) {
commentaire_date_fin_fourniture[i].style.display='block';
}
}
else if($(this).prop("checked") == false){
var commentaire_date_fin_fourniture = document.getElementsByClassName("commentaire_date_fin_fourniture");
for (var i = 0; i < commentaire_date_fin_fourniture.length; i++) {
commentaire_date_fin_fourniture[i].style.display='none';
}
}
});
Working version
hide = function(){
document.getElementsByClassName('xyz')[0].style.display="none";
}
<input class="xyz" type="text"/>
<button onclick="hide();">Click to hide!</button>
If you really want to do things this way, then of course first you need to spell getElementsByClassName correctly; you saw this error in the console, right? Then, you need to know that getElementsByClassName returns an array-like things; you saw that in the documentation, right? So you have to loop over it, or take the first element with [0], or whatever.
But in general, it's bad practice to retrieve elements from the DOM like this and set their styles directly. Instead, take advantage of CSS, which will do 90% of the work for you. Here, I'd use a single higher-level class which controls the behavior, and just set that:
<main id="main">
<div class="xyz"></div>
<main>
Then write your CSS as
main.hide-xyz .xyz { display: none; }
To hide the xyz element, then you need a single JS statement:
document.getElementById("main").classList.add("hide-xyz");
To remove it:
document.getElementById("main").classList.remove("hide-xyz");
Or toggle it:
document.getElementById("main").classList.toggle("hide-xyz");
Once you wrap your head around this style, you'll find yourself writing much less JavaScript that needs to all kinds of DOM lookups and loops and setting of styles.
document.getElementsByClassName always returns an array like object. Specify the array[0] number.
Typescript
let hiddenLocales = document.getElementsByClassName('localeMatch') as HTMLCollectionOf<HTMLElement>;
let hideParentNode = hiddenLocales[0]?.parentElement;
hideParentNode?.remove(); // Remove the element
hideParentNode?.style.display = "none"; // Hide the element

Getting index of element clicked with Array.prototype.indexof.call(); [duplicate]

Lets imagine I have the following HTML code.
I need to find the position within the LI elements for the LI which has the class focus applied.
In this example the result should be 2 (if at 0 index). Any idea how to do it?
<ul class="mylist">
<li>Milk</li>
<li>Tea</li>
<li class="focus">Coffee</li>
</ul>
In pure JavaScript:
var index = 0;
var lis = document.getElementsByTagName('li');
for (var len = lis.length; index < len; ++index) {
if (lis[index].className.match(/\bfocus\b/)) {
break;
}
}
(fiddle)
While you've already accepted an answer to your question, I thought I'd put together a simple index() method for HTMLElements:
HTMLElement.prototype.index = function () {
var self = this,
parent = self.parentNode,
i = 0;
while (self.previousElementSibling){
i++;
self = self.previousElementSibling
}
return this === parent.children[i] ? i : -1;
}
var focus = document.querySelector('li.focus'),
i = focus.index();
console.log(i); // 2
JS Fiddle demo.
References:
Element.previousElementSibling
document.querySelector().
Use .index()
var index = $('.focus').index();
DEMO
Specific list
$('.mylist .focus').index()
DEMO
In jQuery, you should be able to get it, via index. With classes, you could run into issues, when having multiple of them.
I prepared a Plunker, where you can see a solution to the problem.
the expanded version (jquery) would be
$(document).ready(function(){
$('li').each(function(){
var cls=$(this).attr('class');
if(cls=='focus'){
alert($(this).index());
}
});
});

JavaScript DOM - Using NodeLists and Converting to an Array

so I will preface my question with letting you know that this is an assignment for school. I have been working to solve this and I have tried to find the solution within the MDN documentation and I am at a loss. I have to:
Grab a NodeList of bugs
Convert the NodeList to an Array
Here is my index.html file:
<!DOCTYPE html>
<html>
<head>
<title>Bugs in the DOM</title>
</head>
<body>
<div>
<h1>Bugs in the DOM</h1>
<ul>
<li>Horse Flies</li>
<li>Bed bugs</li>
<li>Mosquito</li>
<li>Ants</li>
<li>Mites</li>
<li>Cricket</li>
<li>Woolly Bear Caterpillar</li>
<li>Fleas</li>
<li>Worms</li>
<li>Leeches</li>
</ul>
</div>
<script>
(function() {
// Your code here.
}());
</script>
</body>
</html>
I have been able to grab the li elements, while using the DOM with the following code:
var list = document.getElementsByTagName("ul");
When i call list in the DOM, I am returned the ul, which contains all of the li elements. Not sure if that is what I am supposed to do with respect to the NodeList. I am also confused as to how I can convert the NodeList to an array. Not sure if I need to use a for loop and append each element of the NodeList into a new array? This is all still very new and confusing to me.
Any help is much appreciated, but if you are willing to share insight and an explanation, that would be ideal. I am really trying to wrap my mind around this and I am falling short. Thank you in advance!
You can iterate all the <li> items in each <ul> in the page like this while able to separately tell which <ul> they are in:
var list = document.getElementsByTagName("ul");
for (var i = 0; i < list.length; i++) {
var items = list[i].getElementsByTagName("li");
for (var j = 0; j < items.length; j++) {
console.log(items[j]);
}
}
Or, if you just want all <li> tags, not broken out by <ul>:
var items = document.getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
console.log(items[i]);
}
A nodeList or HTMLCollection can be iterated with a simple for loop as seen above. These objects do not have array methods, but can be copied into an array if you really want to use array methods.
Note, it is probably simpler to use document.querySelectorAll() for listing all the <li> elements and you may want to target a specific <ul> tag by putting an id on it in case there are other <ul> and <li> elements in the page.
<ul id="buglist">
<li>Horse Flies</li>
<li>Bed bugs</li>
<li>Mosquito</li>
<li>Ants</li>
<li>Mites</li>
<li>Cricket</li>
<li>Woolly Bear Caterpillar</li>
<li>Fleas</li>
<li>Worms</li>
<li>Leeches</li>
</ul>
var items = document.querySelectorAll("#buglist li");
for (var j = 0; j < items.length; j++) {
console.log(items[j]);
}
A nodeList or HTMLCollection can be copied into an array like this:
var list = Array.prototype.slice.call(document.querySelectorAll("#buglist li"), 0);
list.forEach(function(item) {
console.log(item);
});

Javascript - Link Name Changing with restrictions

I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/

Categories