3

EDIT: I changed the var to class but I might have some error in here.

Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.

  <script type="text/javascript">
    function changey(){
      var userInput = document.getElementById('userInput').value;
      var list = document.getElementByClassName('kiddo');

      for (let item of list) {
         item.innerHTML = userInput;
      }
    }
</script>

<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>

Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!

No error messages, the code only changes one name instead of all three.

  • Isn't this for javascript tag question not java ? –  Jun 24 '19 at 15:33
  • 1
    IDs must be unique. Use `class="kiddo"` instead -- it will work the same. With IDs, only the first will be found/changed. – cssyphus Jun 24 '19 at 15:36
  • 1
    You may want to use a class instead of an id for this. Then you can use [getElementsByClassName](https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp) to grab them all. – Tim Hunter Jun 24 '19 at 15:36
  • @AmirDanish Looking more closely at your [proposed edit](https://stackoverflow.com/review/suggested-edits/23354734), I think that you had already proposed, and based on the comment in the edit, of changing the tags from Java to JavaScript (which was correct) but the addition of the "function" tag was not needed. I just wanted to call it out in case you thought that the tag *change* was incorrect, only the tag *addition* was really incorrect. – zero298 Jun 24 '19 at 15:51
  • I threw this into my answer, but `.textContent` is better than `.innerHTML` here. – BCDeWitt Jun 24 '19 at 16:35
  • After updating your new code to fix a typo `getElementByClassName` => `getElementsByClassName` (was missing an s), it worked for me. I would be careful of [polluting the global namespace](https://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted) with functions like `changey`, though. – BCDeWitt Jun 24 '19 at 16:41

7 Answers7

3

Use class="kiddo" instead of id in the html.

You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.

Then you just need to loop through the values and change what you want.

Example of loop below:

for (var i = 0; i < kiddos.length; i++) {
     kiddos[i].innerHTML = userInput;
}
Nexevis
  • 4,647
  • 3
  • 13
  • 22
  • Welcome to the site dude This is how you create a document that changes the name of the dude. – marcos kwasniewski Jun 24 '19 at 16:24
  • @marcos kwasniewski Its `getElementsbyClassName` with `Elements` with an `s` – Nexevis Jun 24 '19 at 16:44
1

id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

Hello You should not use id, instead use class.

Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!

After That on Js part :

<script type="text/javascript">
    function changey(){
      var userInput = document.getElementById('userInput').value;
      var list = document.getElementByClassName('kiddo');

      for (let item of list) {
         item.innerHTML = userInput;
      }
    }
</script>
Youssef Najeh
  • 157
  • 1
  • 7
0

try: document.querySelectorAll('.kiddo') with <b class="kiddo">dude</b>

rwest88
  • 9
  • 5
0

you should use class instated of id. if you use id then the id [kiddo] must be unique

Amir Danish
  • 418
  • 5
  • 8
0

In short, document.querySelectorAll('.kiddo') OR document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).

See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):

const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')

const useNameFromForm = (formEl) => {
  const formData = new FormData(formEl)
  const nameValue = formData.get('name')
  const nameEls = getNameEls()
  
  // Set the text of each name element
  // NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
  nameEls.forEach(el => el.textContent = nameValue)
}

// Handle form submit
formEl.addEventListener('submit', (e) => {
  useNameFromForm(e.target)  
  e.preventDefault() // Prevent the default HTTP request
})

// Run at the start, too
useNameFromForm(formEl)
.name {
  font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
  <input name="name" value="dude" placeholder="Name of kid" />
  <button>Change Name</button>
<form>

<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>

var formEl = document.querySelector('.js-name-change-form');

var getNameEls = function getNameEls() {
  return document.querySelectorAll('.js-name');
};

var useNameFromForm = function useNameFromForm(formEl) {
  var formData = new FormData(formEl);
  var nameValue = formData.get('name');
  var nameEls = getNameEls(); // Set the text of each name element

  // NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
  nameEls.forEach(function (el) {
    return el.textContent = nameValue;
  });
};

// Handle form submit
formEl.addEventListener('submit', function (e) {
  useNameFromForm(e.target);
  e.preventDefault(); // Prevent the default HTTP request
});

// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>

<!-- Template to clone -->
<template class="js-quote-template">
    <div class="js-quote-root quote">
        <h2 class="js-quote"></h2>
        <h3 class="js-author"></h3>
    </div>
</template>
BCDeWitt
  • 4,540
  • 2
  • 21
  • 34
  • I didn't include the change in my example code, but wrapping everything with an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) can avoid polluting the global namespace – BCDeWitt Jun 24 '19 at 16:52
0

You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput. See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

harshrd
  • 79
  • 9