-1

It outputs undefined for both. It should output lpoop and /poop. No errors are given

function add() {
  console.log("add")
  var l = document.createElement("img")
  l.setAttribute("src", "/poop")
  l.src = "/poop"
  l.setAttribute("class", "l")
  l.className = "lpoop"
  document.getElementById("b").appendChild(l)
}

function find() {
  console.log("find");
  const elm = document.getElementById("b").firstChild;
  console.log(elm.className);
  console.log(elm.src);
}
<button onclick="add()">
  hi
</button>
<button onclick="find()">
find
</button>

<div id="b">

</div>

If there is any more detail you want pls comment.

Titus
  • 22,031
  • 1
  • 23
  • 33
  • 1
    The problem is that the first child of `#b` is not the image that you've created, it is a text node, to get the image use `firstElementChild` instead of `firstChild`. – Titus Jun 18 '22 at 01:00
  • 1
    Whitespace between elements is considered text nodes. If there is a whitespace before "img" element, the result will be "undefined". – Xupitan Jun 18 '22 at 01:15
  • @MORÈ your changes have removed the problem. – Titus Jun 18 '22 at 01:23
  • @MORÈ No need, I've made an edit myself. – Titus Jun 18 '22 at 01:27

1 Answers1

0

function add() {
  console.log("add")
  var l = document.createElement("img")
  l.setAttribute("src", "/poop")
  l.setAttribute("class", "l")
  document.getElementById("b").appendChild(l)
}

function find() {
  console.log("find");
  const elm = document.getElementById("b").firstChild;
  console.log(elm.getAttribute("src"));
  console.log(elm.getAttribute("class"));
}
<button onclick="add()">
  hi
</button>
<button onclick="find()">
find
</button>

<div id="b"></div>

When you use elem.attr it means that you are getting the JS Attribute of the element, not the HTML attribute.

The .getAttribute() function will get the HTML attribute.

html_coder
  • 163
  • 2
  • 8