JavaScript: The element containing only text

I'm having an issue with the code snippet from the W3Schools website. When I use the LI element in a straight line, it works fine. But when I try to format it differently, it doesn't work. Any ideas on what could be causing this?

This is the code that is not working:

<ul id="myList">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>
<p>Click the button to replace the first item in the list.</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var textnode = document.createTextNode("Water");
    var item = document.getElementById("myList").childNodes[0];
    item.replaceChild(textnode, item.childNodes[0]);
}
</script>

However, this code version does work:

<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

<p>Click the button to replace the first item in the list.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var textnode = document.createTextNode("Water");
    var item = document.getElementById("myList").childNodes[0];
    item.replaceChild(textnode, item.childNodes[0]);
}
</script>

Answer №1

When dealing with the childNodes, it's important to note that it counts not only the visible nodes but also whitespace and comment nodes. For example, in the code snippet below:

<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

The childNodes.length would return 3 for the three li elements. However, in another example producing the same HTML output visually:

<ul id="myList2">
   <!-- a comment node -->
   <li>Coffee</li>
   <li>Tea</li>
   <li>Milk</li>
</ul>

The childNodes.length would actually be 9 due to whitespace and comment nodes being included. This is why it's advisable to use the children property instead.

A straightforward solution to accessing a specific element would be:

document.querySelector("#myList li:first-of-type").innerHTML = "Water"

To handle events more effectively, it's recommended to avoid inline event handling and utilize addEventListener in JavaScript:

<button id="some-id">Try it</button>

<script>
   document.getElementById("some-id").addEventListener(myFunction);
<script>

Lastly, while W3Schools may seem like an official source, it's important to remember they are not affiliated with W3C and have had credibility issues in the past. It might be better to consider other sources for web development information. Check out for more insights.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

Is there a way to verify the presence of months in a column related to departments?

Is there a way to validate whether the current row aligns with the current column month and year? If not, can it be set to 0. Let's consider the current dataset. Presenting my resultData https://pastebin.com/GHY2azzF I want to verify if this data ...

React component failing to update upon rerender

I've encountered an issue with my Flux setup where the component doesn't rerender when adding a new Todo, although it does when deleting or changing the checkbox. I find this behavior confusing and wonder what might be causing it. The list itself ...

Enhance user experience by implementing an autocomplete feature for a text input field

Can you name the process in which a form is automatically filled using database information without needing to refresh the page? One common example of this technique is seen on platforms like Google or Facebook, where they predict friends you may be searc ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

Leveraging Javascript to generate universal HTML content for various Javascript files

Present Situation: I have a timesheet feature that enables users to input their leave, TOIL, and sick days along with the respective hours. Additionally, there is a table that dynamically adds a new row every time the plus button is clicked using the foll ...

The reason behind my unsuccessful attempt to utilize AJAX with the Google GeoChart API

Learning about JavaScript is exciting! I recently tried incorporating a Google Geochart to generate visual reports. The sample code looked like this: function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

Transforming complex nested JSON structures into simple flat JSON using TypeScript and RxJS operators such as map, reduce, and filter

Is there a way to convert the following structure into a simpler one without using complicated foreach loops? It would be great if this can be achieved with existing JS-Libraries like RxJS for Observables, Lodash/Underscore or any similar library. Here is ...

Having trouble printing a section of a webpage after making CSS adjustments

When trying to print part of a page, I used the following method. It successfully prints that portion of the page, however, it does not preserve the CSS effects. <body> <h1><b><center>This is a test page for printing</center&g ...

Concealing a DisplayFor component with the help of Jquery

Hey there, I currently have a 'td' element that appears like this <td style="font-weight:bold"> @Html.DisplayFor(x => x.Parts[i].QtyInItem, new { htmlAttributes = new { @class = "qtyInItem" } }) </td> A ...

Creating a dynamic pulse effect using jQuery to manipulate CSS box-shadow

My goal is to create a pulsating effect using CSS box-shadow through jQuery. Despite my best efforts, the code I attempted failed to produce the desired smooth pulse effect with box-shadow. The code snippet I experimented with: <div class="one"> &l ...

Managing stream pauses and resumes in Node.js using setTimeout()

After some experimentation with Node.js (v4.4.7), I managed to create a simple program to play a sound... const Speaker = require('audio-speaker/stream'); const Generator = require('audio-generator/stream'); const speaker = new Speake ...

Determine the hexadecimal color value by combining two different colors along with a specified percentage/position

Can a color in the middle of a gradient be calculated? var initialColor = 'FF0000'; var finalColor = '00FF00'; // At 50% between the two colors, it would result in '808000' var middleColor = determineMiddleColor(initialColor ...

Retrieve HTML content from a JSON object and render it on a web page

I am facing a challenge with decoding html that is in json format. I'm struggling to figure out how to retrieve my html and display it on a page. It seems like json_decode isn't the solution. Can anyone help me with this issue? Appreciate any as ...

Add a new division to a component when a specific event handler is triggered by another component using React and the reduce method

Currently, I am developing an interactive drag-and-drop application using React and Redux. My goal is to insert a new div element into a container when the ondragstart event handler is triggered by a component. The component responsible for the dragging o ...

Steps to verify the current time and execute a task if it matches the designated time

After successfully implementing a time function which changes the value of an input text based on a specific time, I encountered an issue. Although the time function is designed to change the input text value to 1 when the time reaches 2:30:35 PM... if(b ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Rearrange element's placement using Jquery Drag & Drop

I am experiencing difficulties in positioning my elements after a drop event. Within my "list" of divs... In order to keep the divs together and update the list, I utilize jQuery's append function to move the element from the list to its designated ...

The command is not currently carrying out its function

I am attempting to verify whether the "sender" has either of the two specified roles, but for some reason the command is not being executed. There are no errors showing up in the console, it's just that the command doesn't run. const revAmount = ...