點燈坊

失くすものさえない今が強くなるチャンスよ

Using console.dir to Get The Property of DOM Element

Sam Xiao's Avatar 2021-11-29

If we use console.log to display the DOM element, we will get pure HTML only. What we have to do is using console.dir to get the property of the DOM element.

Version

ECMAScript 2015

console.log

dir000

console.log shows the HTML of the DOM element.

<script setup>
let canvas = $ref (null)

let onClick = _ => {
  console.log (canvas)
  canvas.textContent = 'Hello World'
}
</script>

<template>
  <button @click="onClick">Draw Text</button>
  <div ref="canvas"/>
</template>

Line 4

let onClick = _ => {
  console.log (canvas)
  canvas.textContent = 'Hello World'
}

canvas is a DOM element, and we pass it to console.log but get pure HTML, not the property of the DOM element.

console.dir

dir001

console.dir shows the property of the DOM element.

<script setup>
let canvas = $ref (null)

let onClick = _ => {
  console.dir (canvas)
  canvas.textContent = 'Hello World'
}
</script>

<template>
  <button @click="onClick">Draw Text</button>
  <div ref="canvas"/>
</template>

Line 4

let onClick = _ => {
  console.dir (canvas)
  canvas.textContent = 'Hello World'
}

We use console. dir to replace console.log; now, it displays the property of the DOM element as we expected.

Conclusion

  • For standard Object, there is no difference between console.log and console.dir, but for the DOM element, it’s time to use console.dir

Reference

MDN, console.dir