Issue
The HTML below has a div with id containerId
that has three child div
s. A script tag gets the div with the id and prints out its childNodes
.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Child nodes</title>
</head>
<body>
<div id="containerId">
<div></div>
<div></div>
<div></div>
</div>
<script type="text/javascript">
const element = document.getElementById("containerId");
console.log(element.childNodes)
</script>
</body>
</html>
The result in devtools is
NodeList(7)0: text
1: div
2: text
3: div
4: text
5: div
6: textlength: 7
__proto__: NodeList
Why are those text elements there? I don't see this in a usual setup with all the other frontend layers when I'm using React. What is it that I need to do to avoid this?
Solution
Those are carriage returns or empty spaces in your HTML.
You can use chrome dev tools (View > Developer > Developer Tools
) and click the arrow next to each node after printing it out to console (Console
tab) to see the details.
Here's another tip, if you type $0
in dev console, it will target the exact node you have highlighted in the Elements
pane... This will allow you to debug and investigate easily.
If you don't want that, remove the linebreaks and spaces from HTML like this: <div></div><div></div><div></div>
.
Edit: Ok, there is one trick that you can use to prevent this (based on your comment). This is also used when you are centering items with inline-block
and don't want the space to be visible on the page. You can space it like this:
<div class="wrapper">
<div>Some text</div><div>
Some text</div><div>
Some text</div><div>
Some text</div>
</div>
Answered By - Tallboy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.