Garegin
Garegin

Reputation: 301

Javascript function document.createElement(tagName[, options]) doesn't work as intended

I need to create <a href="http://someurl.com"></a> element in one js code line

this doesn't work:

var gg = document.createElement("a", {href : "http://someurl.com"})

this result in: <a is="[object Object]"></a>

Thought MDN says: var element = document.createElement(tagName[, options]);

options is an optional ElementCreationOptions object. If this object is defined and has an is property, the is attribute of the created element is initalized with the value of this property. If the object has no is property, the value is null. https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

is this ElementCreationOptions object some sort of exotic object? I tried many various combinations around this object but nothing works and always in results i see that strange is property! I also found it in specification: https://www.w3.org/TR/custom-elements/#attr-is but no idea how it actually works.

ps: this doesn't work either:

var gg = document.createElement("a").setAttribute("href" , "someurl.com")

result in undefined.

Upvotes: 27

Views: 40651

Answers (6)

Donatas
Donatas

Reputation: 55

I wanted this functionality too, but found "option" in createElement is not for this. So, I made my own createElement function.

function createElement(name, options) {
    let element = document.createElement(name);
    for (let key in options) {
        element.setAttribute(key, options[key]);
    }
    return element;
}

You can use it like this:

let main = document.getElementById("main");
let input_object = {
    type: "text",
    id: "id-1",
    name: "name",
    class: "cell",
    placeholder: "123456",
    min: "5",
    max: "50",
};

main.appendChild(createElement("input", input_object));

This will return html element with attributes set. You just need to append it to some other element. You can also reuse input_object by changing some of values of attributes and use it again to create new html element.

input_object.id = "id-2";
input_object.placeholder = "9874563"
input_object.readOnly = "";
main.appendChild(createElement("input", input_object));

input_object.id = "name-4";
input_object.placeholder = "qwertyu"
delete input_object.readOnly;
main.appendChild(createElement("input", input_object));

Upvotes: 0

Roman Zenia
Roman Zenia

Reputation: 31

Maybe it will help anyone

((a) => !(a.href = '#link-here') || a )(document.createElement('a'))

Step by step

We just start from anonymous function which invokes itself with param

((param) => /* do some with arg */)(initParam)

Next we initialize an A element and do some with it

((LinkElement) => /* do some with new element */)(document.createElement('a'))

And finally we add href attribute to link like

!(a.href = '#link-here') || a

First we add href in (). It's return us href value and if it's not false we return a element with this changes by ||

Upvotes: 0

Sam Hughes
Sam Hughes

Reputation: 785

I get that this is an ancient question (relatively), and @Luke-Weaver's answer already gave a route involving jQuery, but the following is an option that both accomplishes what @Garegin originally requested, while still giving him the functionality that he wanted from the createElement method's ambiguous parameter name, while using vanilla JS.

gg = Object.assign(document.createElement('a'),{href:'http://someurl.com',innerText:"Bonus points?"});

This solution creates '<a href="http://someurl.com">Bonus points?</a>' on one line. It's longer, so the following might work better:

function oneLineTag(tag,options){
  return Object.assign(document.createElement(tag),options);
}
let quickAnchor = {
  href:'http://someurl.com',
  innerText: "I'm still answering a 3-year-old question"
}

and you now have the option of

gg = oneLineTag('a',quickAnchor);

Upvotes: 36

Naveenk
Naveenk

Reputation: 78

You can not use the second ( ElementCreationOptions ) parameter to add html attributes.

var element = document.createElement(tagName[, options]);

It's clearly mentioned in the documentation that the second optional parameter is an object containing single property i.e. is. As we can see below,

An optional ElementCreationOptions object containing a single property named is, whose value is the tag name for a custom element previously defined using customElements.define(). For backwards compatibility with previous versions of the Custom Elements specification, some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name. See Extending native HTML elements for more information on how to use this parameter.

And coming to your question, the solution can be as below,

var body = document.body || document.getElementsByTagName('body')[0];
var anchor = document.createElement('a');
anchor.href = 'http://someurl.com';

var text = document.createTextNode("http://someurl.com");  
anchor.appendChild(text);
body.appendChild(anchor);

Let me know if it works.

Upvotes: 2

Luke Weaver
Luke Weaver

Reputation: 409

I believe the second parameter of the create element function only applies to custom elements only. Instead you could use the .attr of jQuery to create/set attribute like so:

var gg = $(document.createElement("div")).attr("href", "someurl.com");

If you're not using jquery you might be out of luck (at least if you're trying to get it all on one line). I would have said to use .setAttribute() however I noticed you can't chain that to the end of an object constructor and haven't found a way around this yet.

Upvotes: -2

Taiti
Taiti

Reputation: 377

Try it this way.

var gg = document.createElement("div")
 document.body.appendChild(gg);
var att = document.createAttribute( "href" );
att.value = "someurl.com" ;
gg.setAttributeNode(att); 

Upvotes: -1

Related Questions