简体   繁体   中英

adding a font awesome button to the document

I want to add a font-awesome symbol to a button and then append the button to my page. My code so far:

var rem=document.createElement("button");
rem.setAttribute('value','<i class="fa fa-trash-o" aria-hidden="true"></i>');
document.appendChild(rem);

But it does not work. There's this error on the console:

Failed to execute 'appendChild' on 'Node': Only one element on document allowed.

So how do i achieve this? I am ok with using other code such as jQuery, etc

Two things...

The first is how you're attempting to add the icon to the button. By using rem.set('value', '...') you're basically saying the output should be

<button value="<i class="fa fa-trash-o" aria-hidden="true"></i>"></button>

...but what you really want is...

<button><i class="fa fa-trash-o" aria-hidden="true"></i></button>

To achieve this use rem.innerHTML = '...'

And secondly, you're trying to append to the document which is not valid which is why you're getting the error "Failed to execute 'appendChild' on 'Node': Only one element on document allowed.".

What you want is to append it to the <body> or another element on page, you can do this with document.body.appendChild(rem) . See below for resolved code.

var rem = document.createElement('button');
    rem.innerHTML = '<i class="fa fa-trash-o" aria-hidden="true"></i>';
document.body.appendChild(rem);

And if you're already using jQuery you can do the following...

var rem = $( '<button><i class="fa fa-trash-o" aria-hidden="true"></i></button>' );
$('body').append(rem);

Hope this helps!

You have two issues here. Firstly the cause of the error is because you cannot append a button element to the document . You need to append it to an element within the body . In the example below I used the body itself, but any will work.

Secondly you need to set the <i> element containing the icon as a child of the button you create, not the value attribute.

 var rem = document.createElement("button"); rem.innerHTML = '<i class="fa fa-trash-o" aria-hidden="true"></i>'; document.body.appendChild(rem);
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM