append() or appendTo() for fontawesome

6.8k views Asked by At

I have this scenario.

In title <h2></h2> I want to put fontawesome icon before text. Ex.

  <h2 id="test"><i class="fa fa-cog"></i> THIS IS TITLE</h2>

I will add manual icon for all title, but if any title stay empty (without icon), the script add default icon

  <i class="fa fa-angle-double-left"></i>

I have tried with this script but it is not working.

$("#test(:empty)").append('<h2><i class="fa fa-angle-double-left"></i></h2>');

Any suggestion to fix this problem?

Edit This one i need for all blocks in sidebar. Structure of block's is:

        <div class="sidebar">
        <h2><i class="fa fa-users"></i><a href="#"> Title 1</a></h2>
        <ul>
                        <li>

                            <div class="user"></div>
                        </li>
        </ul>
    </div>

And 2-nt sidebar same class different title

        <div class="sidebar">
        <h2><i class="fa fa-users"></i><a href="#"> Title 2</a></h2>
        <ul>
                        <li>

                            <div class="user"></div>
                        </li>
        </ul>
    </div>

And block 3-th is without icon

        <div class="sidebar">
        <h2>HERE ADDD DEFAULT ICON <a href="#"> Title 1</a></h2>
        <ul>
                        <li>

                            <div class="user"></div>
                        </li>
        </ul>
    </div>    

I hope now is clear

3

There are 3 answers

1
Geoffrey On BEST ANSWER

You can do it with CSS using Pseudo-Classes.

.sidebar h2:empty:before {font-family: 'FontAwesome';content: '\f100';}
.sidebar h2:before {font-family: 'FontAwesome';content: '\f0c0';}

<div class="sidebar">
    <h2>User Name</h2>
</div>

JSFiddle

0
StaticVoid On

You are appending an h2 to an h2. Better yet, set your html to:

$("#test(:empty)").html('<i class="fa fa-angle-double-left"></i>');

Also, you should not give multiple elements the same id. For this, you should use a class and call like:

$(".test(:empty)").html('<i class="fa fa-angle-double-left"></i> My default title!');
0
Shaunak D On

in title <h2></h2> i want to put fontawesome icon before text

$("h2(:empty)").html(function(){
    return "<i class="fa fa-angle-double-left"></i>"+this.innerText;
});

Note $('#test(:empty)') will search for the first element with #test,and I guess you already have one h2 non-empty.

You should not have elements with same IDs, it must be unique in a document. Use data-* attributes - data-id

<h2 data-id="test">....

$("h2[data-id='test'](:empty)")

or class

<h2 class="test">....

$("h2.test(:empty)")