Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript DOM Scripting By Example Improving the Application Code Next Steps

karan Badhwar
karan Badhwar
Web Development Techdegree Student 13,000 Points

accessing Text Nodes

Why this one is not working

  const checkbox = e.target;
  let labelText = checkbox.parentNode.textContent;
      if (checkbox.checked){
             labelText = 'Confirmed';
  } else {
      labelText = 'Confirm';

But this code is working

if (checked){
 checkbox.parentNode.parentNode.className = 'responded';
    labelText.textContent = 'Confirmed';
  } else {
    checkbox.parentNode.parentNode.className = '';
      labelText.textContent = 'Confirm'

Can somebody please explain me this having hard time understanding and how do we actually access and manipulate Text Nodes when they have sibling Element Nodes with them?

1 Answer

Steven Parker
Steven Parker
216,175 Points

DOM traversal allows you to isolate and manipulate specific nodes, so it won't matter if they have any sibling nodes or not.

As to the code examples, you didn't say but I assume that by "working" you mean "able to make changes to the DOM". If so, the problem with the first example is that it only assigns a variable, it doesn't address anything in the DOM:

  let labelText = checkbox.parentNode.textContent;  // this COPIES the text into "labelText"
             labelText = 'Confirmed';               // this only reassigns the variable

But the second example modifies the DOM:

let labelText = checkbox.parentNode;      // this wasn't shown, but I'm assuming that this
//...                                        time "labelText" refers to the element node
    labelText.textContent = 'Confirmed';  // so this changes the text in the DOM