2

I get a array from my database and i m trying to create a element but it's not working. this is my simplify code

var objecthtml = {

	id : 1,
	html: '<div> </div>',
	css: 'colonne'
}

console.log(objecthtml.html);
console.log(objecthtml);

var myArray = [objecthtml];
console.log(myArray);

let block =  document.createElement(objecthtml.html);

this is the error message :

InvalidCharacterError: String contains an invalid character

3
  • 2
    Try to use just html: 'div' in objecthtml Commented Jun 26, 2018 at 8:05
  • i can't change my array because it's register in my database like that and i have the work with this data type Commented Jun 26, 2018 at 8:09
  • @hlklbklk: You can try my updated anwer Commented Jun 26, 2018 at 8:29

3 Answers 3

2

document.createElement takes a HTML tag name as a parameter. If you want to create an element with the HTML code that's in your object's property, you can create a container element and put that HTML code in its innerHTML property.

var objecthtml = {
	id : 1,
	html: '<div>Oh yeah</div>',
	css: 'colonne'
}

let block =  document.createElement("div");
block.innerHTML = objecthtml.html;

document.body.appendChild(block);

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

Comments

0

To create an element you just use the tag name like p, div, h1 etc.

And exceptions clearly says that about bad tag name

var objecthtml = {

	id : 1,
	html: 'div',
	css: 'colonne'
}

console.log(objecthtml.html);
console.log(objecthtml);

var myArray = [objecthtml];
console.log(myArray);

let block =  document.createElement(objecthtml.html);

Comments

0

You can refer to documentation, the parameter that expecting is tagName which is div but you passed in <div> </div>

var newDiv = document.createElement("div");

So instead you can try following

var objecthtml = {

	id : 1,
	html: '<div> </div>',
	css: 'colonne'
}

let rgx = /^(.+\s)|(?:=["'\s]?)(.*)(?:["'\s>]?)/g;
let fullTag = rgx.exec(objecthtml.html)[0].trim();
var realTag = fullTag.substring(1,fullTag.length-1);
let block =  document.createElement(realTag );

2 Comments

i know that but i can't change the objecthtml
@hlklbklk: Please try my updated answer which using the regex to grab the tag since you mentioned you can't change the objecthtml

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.