raj
raj

Reputation: 33

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]?

Code: In the console of chrome developer tool

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

Output a:

Code:

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

Output div: [object HTMLDivElement]

Upvotes: 3

Views: 187

Answers (1)

adeneo
adeneo

Reputation: 318182

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: ')
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

Upvotes: 1

Related Questions