Issuse with DOM properties

given this html

 <header>
    <h1 id="title">Triathlon</h1>
  </header>
  <section id="sports">
    <p class="swim">Swim</p>
    <p id="bike">Bike</p>
    <p>Run</p>
    <h3> js output follows ******* </h3>
  </section>

// these don’t work
swim.firstChild; undefined
swim.parentNode; undefined
swim.nextSibling; undefined
swimTextNode = swim.firstChild; undefined
swimTextNode.nodeValue; can’t read undefined
swim.textContent; undefined
swim.getAttribute(“class”); not a function

according to the book I’m reading “Javascript Novice to Ninja” swim( which is a class name) should work as well as bike ( an id name) but the id name works anc the class name doesn’t. I think this is probably an error on the authors part. What’s even stranger is that the last paragraph

Run

which has no id or class can be accessed with run, run isn’t listed in the code the text of the paragraph is of course Run with uppercase R yet if I enter “run.firstChild” or “run.textContent” it treats run as a legitimate identifier.

1 Like

You can’t use that because there can be more than one element with that class.

You can do something like this…

var swim = document.getElementsByClassName('swim')[0];    // if you want the first element....

2 Likes

Presumably you are working with Internet Explorer as only that browser has the behaviour you are describing. That’s the only browser that pollutes the global namespace like that so presumably the author only used that browser as well.

Thank you that’s all it was.

I was doing this one command at a time in the console I forgot that I had already run run=document.querySelector(‘p:last-child’); followed by run.setAttribute(“id”.“run”); I was confused … thanks for your help

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.