raj raj - 17 days ago 4x
HTML Question

anchor element creation javascript

I had created an anchor element using createElement() (in both chrome and firefox developer tools) and when I try to display the element in the console, I find blank. When trying the same with div element creation, I can see the element displayed in console correctly. Below is the actual code and output. What is the reason for this? Should not the anchor element output as a: [object HTMLAnchorElement]?

In the console of chrome developer tool

var anchor = document.createElement(‘a’)
console.log(‘anchor: ‘ + anchor)



var div = document.createElement('div')
console.log(‘div: ‘ + div)

div: [object HTMLDivElement]


The anchor is there, you're just using the console incorrectly.

You're concatenating a string with an object, and anchor.toString() returns an empty string, while with a DIV it would return [object HTMLDivElement].

To solve it, just use the console correctly, either log them seperately

var anchor = document.createElement('a')
console.log('anchor: ')

or use a comma as a seperator

var anchor = document.createElement('a')
console.log('anchor:', anchor)

and you'll log the object as an object, not as a string