Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Improving the Application Code Next Steps

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 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';
      console.log(labelText);
    }
 });

But this code is working

if (checked){
 checkbox.parentNode.parentNode.className = 'responded';
    console.log(labelText);
    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
229,744 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