I'm a rookie. I try this example to test code that when click on each p ,the section text will replace by "yeah"
When click first p, first section is replaced
When click 2nd p, 2nd section is replaced ...
Code like this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>p{text-align: center;}</style>
</head>
<body>
<p class="test">hello</p>
<p class="test">how</p>
<p class="test">are</p>
<p class="test">you</p>
<p class="test">today</p>
<p class="test">sir</p>
<section>good</section>
<section>great</section>
<section>excellent</section>
<section>well</section>
<section>best</section>
<section>better</section>
<script>
var x = document.getElementsByClassName("test")
var y = document.getElementsByTagName("section")
for(i=0;i<y.length;i++){
y[i].setAttribute("class","linktest")
}
var z = document.getElementsByClassName("linktest")
function place(a){
z[a-1].innerHTML="yeah"
}
for(i=0;i<x.length;i++){
x[i].addEventListener("click", function(){
place(i+1)})
}
</script>
</body>
</html>
how i wrong with for loop code of addEventListener
I try to write long code like this
x[0].addEventListener("click",function(){place(1)})
x[1].addEventListener("click",function(){place(2)})
x[2].addEventListener("click",function(){place(3)})
x[3].addEventListener("click",function(){place(4)})
x[4].addEventListener("click",function(){place(5)})
x[5].addEventListener("click",function(){place(6)})
And it worked but i want to short code because real work has mor than 100 items
Help plz
#Chaska's answer works fine but since you mentioned that there will be over 100 items it's important to avoid adding event listeners for each element for better performance. Instead wrap all the p tags in a div and add a single event listener to the div tag. Here is a slightly modified code.
var x = document.getElementsByClassName("test");
var y = document.getElementsByTagName("section");
for (i = 0; i < y.length; i++) {
//assuming equal no. of elements in x and y
y[i].setAttribute("class", "linktest");
x[i].setAttribute('data-index', i);
}
var z = document.getElementsByClassName("linktest");
function place(a) {
z[a].innerHTML = "yeah";
}
var testGroup = document.getElementById('test-group');
testGroup.addEventListener('click', function() {
place(parseInt(event.target.getAttribute('data-index')));
})
<div id="test-group">
<p class="test">hello</p>
<p class="test">how</p>
<p class="test">are</p>
<p class="test">you</p>
<p class="test">today</p>
<p class="test">sir</p>
</div>
<section>good</section>
<section>great</section>
<section>excellent</section>
<section>well</section>
<section>best</section>
<section>better</section>
You are calling place() function out of the for loop. So the value of i will always be 6.
Try this way to assign the index to each element first and pass it to the place() function.
var x = document.getElementsByClassName("test");
var y = document.getElementsByTagName("section");
for (i = 0; i < y.length; i++) {
y[i].setAttribute("class", "linktest");
}
var z = document.getElementsByClassName("linktest");
function place(a) {
z[a].innerHTML = "yeah";
}
for (i = 0; i < x.length; i++) {
x[i].setAttribute('data-index', i);
x[i].addEventListener("click", function() {
place(parseInt(this.getAttribute('data-index')));
})
}
<p class="test">hello</p>
<p class="test">how</p>
<p class="test">are</p>
<p class="test">you</p>
<p class="test">today</p>
<p class="test">sir</p>
<section>good</section>
<section>great</section>
<section>excellent</section>
<section>well</section>
<section>best</section>
<section>better</section>
Related
I am trying to figure out a way to count words that are placed in multiple paragraph blocks in javascript. Right now I have a button that is connected to a function and that function is linked to an ID in the paragraph. Here is my code
function processText(elements) {
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(/\s/).length;
}
return count;
}
var wordsInParagraphs = processText(document.getElementsByTagName("data"));
<!DOCTYPE html>
<html>
<head>
<meta name="title" content="The Cask of Amontillado--Edgar Allan Poe (1809-1849)">
</head>
<body>
<p><button 1="processText(elements);">Process</button></p>
<p id="data"></p>
</body>
Is this what you're looking for? You just need to call the function on click and grab all the elements you want to count, you have the rest there (I'm using split instead of regex).
function processText() {
var elements = document.querySelectorAll(".data");
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(" ").length;
}
console.log(count)
}
<!DOCTYPE html>
<html>
<head>
<meta name="title" content="The Cask of Amontillado--Edgar Allan Poe (1809-1849)">
</head>
<body>
<p><button onclick="processText();">Process</button></p>
<p class="data">text in paragraph one</p>
<p class="data">text in paragraph two</p>
</body>
The markup has some problems, for example, 1="processText(elements);" probably you meant onClick="processText(elements);", however, you're passing a param called elements. Further, you have a tag with id="data" and you're trying to look for tag name those elements.
A better approach is using the function addEventListener for a better logic and you should mark those paragraphs using a class name class="data". Finally, for splitting by spaces use this regex /\s+/
function processText(elements) {
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(/\s+/).length;
}
return count;
}
document.getElementById('myButton').addEventListener('click', function() {
var wordsInParagraphs = processText(document.getElementsByClassName("data"));
document.getElementById('total').textContent = wordsInParagraphs;
});
<p><button id='myButton'>Process</button></p>
<p class="data">Ele from Stack</p>
<p class="data">Ele from Venezuela</p>
<p id='total'></p>
I have a problem with my JavaScript function, in the "for" part it doesn't recognize the HTML elements when I use i to refer to the list position, but when I use [0] or [1], for example, it does recognize it. So there must be a problem with the loop part but I can't figure out what is it, here is the code:
(function () {
"use strict";
window.animacion_click_menu = function (id) {
var i;
var menu = document.getElementById('menu').getElementsByTagName('LI');
var bloqueActual = document.getElementById(id);
for (i = 0; i <= menu.length; i++) { //recorre los LI devolviendolos a su posicion original
menu[i].style.marginLeft = -40;
menu[i].style.opacity = 1;
}
bloqueActual.style.marginLeft = 200;
bloqueActual.style.opacity = 0;
};
})();
and here's my html:
<head>
<meta charset="UTF-8">
<title>Mario Luque Marchena</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/estilos.css">
</head>
<body>
<center>
<h1 class="titulo">Bienvenid#</h1>
</center>
<div id="main-screen">
<ul id="menu">
<center>
<li id="sobremi" onclick="window.animacion_click_menu('sobremi');">Sobre mi</li>
<li id="portafolios" onclick="animacion_click_menu('portafolios');">Portafolios</li>
<li id="animacion" onclick="animacion_click_menu('animacion');">Animacion</li>
<li id="back-end" style="border-bottom-style: dashed;" onclick="animacion_click_menu('back-end');">Back-End</li>
</center>
</ul>
</div>
<script type="text/javascript" src="js/animaciones.js"></script>
</body>
if you have any suggestions to make the code better, are welcome too, i'm learning to code. thank you!, and sorry for the bad english in case it was
Your error is really on the for loop.
Take a look on:
for (i = 0; i <= menu.length; i++) {
it should be:
for (i = 0; i <= menu.length-1; i++) {
Otherwise, it will try to iterate from 0 to 5 while your menu array has only 4 items.
The result is that in the last iteration, when you try to access the element menu with the inexistent index (menu[5]) you get the error:
Uncaught TypeError: Cannot read property 'style' of undefined
Other possibility to overcome this is to change <= to < and work with the loop as:
for (i = 0; i < menu.length; i++) {
use window.onload() or
$('document').ready(function(){
//Put your code here
})
I think your code is getting executed before DOM creation.
I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}
I am trying to create an html page that contains a title, and when we click on the title it generates words underneath it. But the code I have is only working for the first click, and it's also deleting the title. So my question is, how can I make it generate words under the title without deleting it?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script>
var k = 0;
function bla(){
var ph = ["red ","blue","black","green","yellow"];
if(k <= ph.length ){
document.write(ph[k]);
k++;
}
}
</script>
</head>
<body>
<h1 onclick="bla();">Click here</h1>
</body>
</html>
Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. This is almost certainly not what you intend to have happen. You should therefore avoid using document.write in situations such as this
so try add a element and then write into them like this
<h1 onclick="bla();">Click here</h1>
<span id="test"></span>
JS:
if(k <= ph.length ){
//document.write(ph[k]);
document.getElementById("test").innerText+=" "+ ph[k];;
k++;
}
JS Fiddle Example
This may be what you need:
var k = 0;
function bla() {
var ph = ["red", "blue", "black", "green", "yellow"];
if (k < ph.length) {
var p = document.createElement('p');
p.innerHTML = ph[k];
document.body.appendChild(p);
k++;
}
}
http://jsfiddle.net/p5rLX/
It will write each word into its own paragraph.
I've written this sample code to print the length of x. But for some reason, I am not getting anything! Help!
<html>
<head>
<script type = "text/javascript">
function myF()
{
var x = [1,2,3,4];
var y = document.getElementById("thing");
y.innerHtml = x.length;
}
</script>
</head>
<body onload = "myF();" >
<div id = "thing" >
PRINT TEST
</div>
</body>
</html>
The property name is innerHTML rather than innerHtml.