why document.getElementsByName().length always return 0? - getelementsbyname

I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many <li>-tags in my HTML, why?
document.addEventListener('DOMContentLoaded', function() {
var len = document.getElementsByName('li').length;
alert(len);
})
art of my HTML:
<body>
<ul>
<li>aaaaaa</li>
<li>bbbbbb</li>
<li>cccccc</li>
</ul>
</body>

Replace
document.getElementsByName('li')
with
document.getElementsByTagName('li')
This is happening cause you are selecting by tag name and not by name ! You are using wrong function!

The method you are attempting to use is trying to find a specific element by its name.
None of your list items have a name, to do this you should update your code so that your items have names.
document.addEventListener('DOMContentLoaded', function() {
var len = document.getElementsByName('list_item_1').length;
alert(len);
})
<li name="list_item1">aaaaaa</li>

You can do something like this because getElementsByTagName() returns NodeList so you can iterate over it like an array or get the length.
document.addEventListener('DOMContentLoaded', function() {
var listElements = document.getElementById('list').getElementsByTagName("li");
alert(listElements.length);
})
<body>
<ul id="list">
<li >aaaaaa</li>
<li>bbbbbb</li>
<li>cccccc</li>
</ul>
</body>
getElementsByName() although also returns NodeList but it returns list of all same name elements in the whole document so to make this work you need to give same name to all list items.
document.addEventListener('DOMContentLoaded', function() {
var len = document.getElementsByName('name').length;
alert(len);
});
<body>
<ul>
<li name="name">aaaaaa</li>
<li name="name">bbbbbb</li>
<li name="name">cccccc</li>
</ul>
</body>

Related

Attempting to remove anchor tags from the URL

Situation: I want to remove the anchor tags ( #tag ) from the end of the URL
What I have tried: I have been following "https://www.finsweet.com/hacks/15/" and "https://stackoverflow.com/questions/34175285/removing-anchor-tags-from-url". Its not working out very well though.
Code:
My snippet from the top nav bar
<ul class="nav">
<li class="scroll-to-section">
Home
</li>
</ul>
My use of Id
<div class="main-banner header-text" id="top">
Maybe the way i approached the edits to the navigation bar is wrong.. but im not sure what i need to to do to achieve the goal. Or how I used the classes and IDs is possibly incorrect?
--- Edit 1 ---
this is the snipper of the script im attempting to use to remove the anchor tag from the URL bar of a brower.
$("#js-anchor").click(function (evt) {
evt.preventDefault();
var anchor = $(this).text();
$("html, body").animate(
{
scrollTop: $("#" + anchor).offset().top,
},
1500
);
});
And the html im looking at
<li class="scroll-to-section">
<a id="js-anchor" href="#testimonials" class="active"
>staff</a>
</li>
The experment on it is here:
https://the-md.studio/indexhash.html
EDIT2
My new attempt
<li class="scroll-to-section">
Home
</li>
JS
$(document).ready(function () {
// get the anchor link buttons
const menuBtn = $(".scroll-to");
// when each button is clicked
menuBtn.click(() => {
// set a short timeout before taking action
// so as to allow hash to be set
setTimeout(() => {
// call removeHash function after set timeout
removeHash();
}, 5); // 5 millisecond timeout in this case
});
// removeHash function
// uses HTML5 history API to manipulate the location bar
function removeHash() {
history.replaceState(
"",
document.title,
window.location.origin + window.location.pathname + window.location.search
);
}
});
Just saw this Q. I guess this is what you tried to ask:
// first: get the full url
var hash_url = window.location.href;
// second: simply do a split
// can't go wrong here, because url's that show content are always in correct format
hash_url = hash_url.split('#'); var clean_url = hash_url[0];
alert(clean_url);
There's your clean url!

How would I efficiently toggle different divs using an h tag?

I am attempting to show a certain div when the relative li is selected. If any other divs are showing, I need to hide that one and only display the new one. There 1000% is a way more efficient way to do this then creating many useStates.
import {useState} from 'react'
import './dope.css'
export const PageContent = () => {
const [one, setOne] = useState('false')
const [two, setTwo] = useState('false')
function toggle1(){
set1(!1)
}
function toggle2(){
set2(!2)
}
return (
<section>
<div className='middle_wrapper'>
<div className='left_menu_wrapper'>
<nav className='nav_black'>
<li><a href='#!' onClick={toggle1}>1</a></li>
<li><a href='#!' onClick={toggle2}>2</a></li>
<li><a href='#!'>3</a></li>
<li><a href='#!'>4</a></li>
<li><a href='#!'>5</a></li>
<li><a href='#!'>6</a></li>
<li><a href='#!'>7</a></li>
<li><a href='#!'>8</a></li>
<li><a href='#!'>9</a></li>
<li className='no_border'><a href='/'>10</a></li>
</nav>
</div>
<div className='right_content'>
<section className='full_page'>
<div id='new_res' className={one? 'inactive' : 'active'}>
<h1>This is a 1 test</h1>
</div>
<div id='all_res' className={two? 'inactive' : 'active'}>
<h1>This is a 2 test</h1>
</div>
</section>
</div>
</div>
</section>
)
}
---- From dope.css ----
.active {
display: block;
}
.inactive {
display: none;
}
--------
https://gyazo.com/1838ccf473832a00f341f4366b97b670
Like above, I would like to make this more efficient, it's probably something very simple that I am overlooking because I am tired and need sleep. I think I could simply just toggle the div's using href='#new_res' but how would I keep it hidden if it's not in use?
Any help would be appreciated, I know this is something simple and I by time someone answers, I may have found the solution. If not, thank you for helping!
If possible, it would be more efficient to simply use a checkbox.
However, if you have to use React state for flexibility, you could make a state with an array instead:
const [checkedArray, setCheckedArray] = useState([])
Whenever there is a new div to check toggle state, push a false into the array, when it is clicked, turn it to be true:
// Example
// Adding new state
setCheckedArray((current)=>[...current,false])
// Mutating 3rd item's state
setCheckedArray((current)=>{
const newArray = [...current];
newArray[3] = true;
return newArray
})
// Getting the info of the 3rd item of the array
const stateOfThirdItem = checkedArray[3]
Create a state to store all the components and their visibility flag. This will allow you to loop through them to dynamically render the anchors (and their onClick event) and also show them in the DOM.
https://codesandbox.io/s/so-71716290-bdsp9w?file=/src/PageContent.js

How to apply a style on links with querystrings

So basically if you want an indicator on the link of the page you are currently on you just apply a style on the page for example:
<li>HOME</li>
<li>ABOUT</li>
<li>CONTACT</li>
It will apply whatever style is on the class active when you are in the home.aspx page...
Now I have something similar but this time, instead of directing to another page, the links will just redirect on the same page but filtered with querystrings...
I have:
<li>PROJECT 1</li>
<li>PROJECT 2</li>
<li>PROJECT 3</li>
What I would like to happen is I want to apply a css style when I click one of those links so that people know which project they are looking at.
Just add a little jquery to add the .active class to selected element.
<script>
jQuery(function($){
var url = window.location.href;
// give the li or a tag a class
$('.element-class-name a[href="'+ url +'"]').addClass('active');
$('.element-class-name a').filter(function() {
return this.href == url;
}).addClass('active');
});
</script>
Try caching selector $("a[href^=projects]") as variable , attach click event to cached selector , utilize .each() to iterate all elements in collection , set className to "active" if this current element === event.target
var a = $("a[href^=projects]");
a.click(function(e) {
a.each(function() {
this.className = this === e.target ? "active" : ""
})
})
var a = $("a[href^=projects]");
a.click(function(e) {
// Note, `e.preventDefault()` included for stacksnippets
e.preventDefault();
a.each(function() {
this.className = this === e.target ? "active" : ""
})
})
a.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>PROJECT 1
</li>
<li>PROJECT 2
</li>
<li>PROJECT 3
</li>
</ul>
Doing something like the following works also:
$('.link').on('click', function(e) {
$('.links li .link').removeClass('active');
$(this).addClass('active');
});
Where link is the class I gave the actual link within a list called links.
The example is here: http://codepen.io/anon/pen/OyJgBQ

Add PREV and NEXT to an HTML5 Page That's Using IFrame

I have an HTML5 webpage with an iframe in the center of it.
Different pages load within the iframe when the numbered links are clicked.
These numbered links are on the initial HTML5 page (below the iframe tag).
I'd like to have a working PREV and NEXT link beside the numbered links but don't know how to do it.
This is what I have so far:
<div>
<nav>
<ul>
<li class="prev">« Previous</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li class="next">Next »</li>
</ul>
</nav>
So the issue I have is that I don't know how to tell the PREV link to load the previous IFRAME and the same for the NEXT link.
Any help would be appreciated.
solved this using the Javascript function incrementId() already found to exist else where in stackoverflow itself. I cloned this and slightly tweaked to decrementId. These functions take a parameter (like this: "news-pg1") and increments to news-pg2 to which ".html" can be appended and so on and then loads the iframe with the html content.
added an click event handler to list tag.Added two functions SetPrev and SetNext to handle frame loads
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var f='news-pg1';
function newContent() {
document.getElementById('fr_content').src =f+ ".html";
}
function decrementId(id) {
// regexp is looking for text with a number suffix. adjust accordingly.
var numberSuffixRegExp = /(.*?)(\d*)$/;
var regExpMatch = numberSuffixRegExp.exec(id);
// assuming a match will be made here, and position 1 and 2 are populated.
var prefix = regExpMatch[1];
var counter = parseInt(regExpMatch[2]);
if (counter > 1)
counter--;
return prefix + counter;
}
function incrementId(id) {
// regexp is looking for text with a number suffix. adjust accordingly.
var numberSuffixRegExp = /(.*?)(\d*)$/;
var regExpMatch = numberSuffixRegExp.exec(id);
// assuming a match will be made here, and position 1 and 2 are populated.
var prefix = regExpMatch[1];
var counter = parseInt(regExpMatch[2]);
if (counter < 3) {
counter++;
}
return prefix + counter;
}
function setNext() {
try {
f=incrementId(f);
document.getElementById('fr_content').src=f+".html";
} catch(e) {
ErrorHandler.handleError(e);
}
} //setNext
function setPrev() {
f=decrementId(f);
document.getElementById('fr_content').src=f+".html";
}
</script>
<head>
<body>
<div>
<nav>
<iframe id="fr_content" src="news-pg1.html" width=300 height=200>
</iframe>
<ul style=list-style-type: inline;>
<li onclick="setPrev();"> <u>Prev </u> </li>
<li onclick="setNext();"> <u>Next </u> </li>
</ul>
</nav>
</div>
</body>
</html>

Target to a page inside an iframe

I will try to explain again:
I have 3 images in my index.html that when clicked i'd like to point respectively to ourmission.html, ourvalues.html and ourvision.html.
But this 3 pages are inside an iframe located in the page ourcompany.html as you can see below:
<aside class="sidebar">
<h4>Our Company</h4>
<ul class="nav nav-list primary pull-bottom">
<li>Contact Us</li>
<li>Our Mission</li>
<li>Our Values</li>
<li>Our Vision</li>
</ul>
</aside>
<iframe src="contactus.html" frameborder='0' name="conteudo" width="700" height="700">
</iframe>
How do i to point them directly, so the page ourcompany.html will load with the specific iframe opened.
This might be a possible solution for you, if I have understood you correctly.
I am assuming you dont have a server set up with the website.
In your index.html, your image links need to be modified to this:
<img src="" />
<img src="" />
<img src="" />
Notice the ?link=someValue after the ourcompany.html link. This is a GET request but you will use it to pass data between pages.
Now in your ourcompany.html page you need to get the value you sent after the ?link=. So you need to add some Javascript. This is the function you need to add to ourcompany.html:
function getValue()
{
// First, we load the URL into a variable
var url = window.location.href;
// Next, split the url by the ?
var qparts = url.split("?");
// Check that there is a querystring, return "" if not
if (qparts.length == 0)
{
return "";
}
// Then find the querystring, everything after the ?
var query = qparts[1];
// Initialize the value with "" as default
var value = "";
var parts = query.split("=");
// Load value into variable
value = parts[1];
// Convert escape code
value = unescape(value);
// Return the value
return value;
}
Now you can change the iframe src attribute accordingly like this:
var link = getValue();
if (link.length){//check if you got a value
document.getElementByName('conteudo').src = link + ".html";//set the src
}
I got the solution adding the following code to the page where the iframe is located:
<script>
window.onload = function loadIframe(){
if (location.search.length > 0){
url = unescape(location.search.substring(1))
window.frames["iframe-name"].location=url
}
}
</script>
and using the href as:
<a href="iframe-page.html?specific-iframe.html">
Thanks a lot for everyone that tried to help me.