0

I have multiple divs in my htmlthat needs to have an element added between the div and p

<div class="ui-state-error ui-corner-all">
 <p><b>Reversed</b></p>
</div>

what i want is the html to add the a span between the two

<div class="ui-state-error ui-corner-all">
<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
 <p><b>Reversed</b></p>
</div>

But the functions ive tried have not been able to do this for each class once, if there are 13 classes, the function puts 13 s on each of the 13 classes, regardless if i just use a selector or an each(), insertBefore(), before(), after(), ect

here is what ive tried that hasnt worked

 <script type="text/javascript">        
       $(function () {                 
html = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>';

           $('.ui-state-error').each(function(i){
                $('.ui-state-error').eq(i).before('p').append(html);
            });
        });
    </script>

3 Answers 3

3

Try to do this :

$(document).ready(function(){
    html = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>';
    $('.ui-state-error').prepend(html);
});

Here is the documentation about prepend

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

3 Comments

it still adds the element multiple times per class, and erases the existing <p> , i havent been able to figure out how to iterate through each class and add an element between elements
It should, i've just tried this. Be sure the code is not executed many times !
the code is being executed multiple times , wasnt the append or prepend executing multiple, the code was. thank you
1

Try this,

Live Demo

     $(function () {                 
html = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;">your span</span>';

           $('.ui-state-error').each(function(i){
                $(this).prepend(html);           
            });

        });​

Comments

1

This may work for you:

$(function(){ html = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>'; $(html).prependTo('.ui-state-error'); });

My answer is similar with PoulsQ's. But the different is $.prepend() is for only one matched element (I think that is the first matched element), while $.prependTo() is prepending to all matched elements. This rule is also worked for append() and appendTo(); before() and insertBefore(); after() and insertAfter();

Hope this can be helpful.

Comments

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.