0

I am making a javscript library like reactJS. And, I am stuck with a problem.

//how to get the name of an element created in javascript in another function without parameter

//Example
let demo = document.createElement("div"):

function example(element){
  // this will get the name of the element ,ie.., div
  console.log(...)
  //should print "div" on the console
}
example(demo);

Can anybody help me?

Edit: This is just an example. The libray is more complex and long that I cant add it here.

6
  • what is you expected output? Commented Dec 11, 2022 at 11:49
  • It's not clear what you need.. In "function example" the variable "demo" is visible, so you can print it. Commented Dec 11, 2022 at 11:49
  • 1
    console.log(element.nodeName);. Commented Dec 11, 2022 at 11:55
  • May I ask what the use-case for this is? The element-type (div, span, input...) is trivially obtained from a property of the given element (which may make the use of a function unnecessary), also: if you're creating the element (particularly if that's within the same function/context) doesn't your code already "know" what element it's creating? Commented Dec 11, 2022 at 12:05
  • This is just an example. The library I am making is more complex. Commented Dec 11, 2022 at 12:06

1 Answer 1

1

Try to get the element.localName, element.nodeName or element.tagName:

function example(element){
  console.log(element.localName); // should print 'div'
  console.log(element.nodeName); // should print 'DIV'
  console.log(element.tagName); // should print 'DIV'

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help! This will help my library to function more powerfully with shorter code.
Bear in mind that there's also element.tagName, though you may want to use element.tagName.toLowerCase() to retrieve the lowercase name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.