-1

i have following HTML element:-

<a href="http://localhost/wordpress/post-2/#more-4" class="more-link">

I tried to add a button before span (put span between button) with jQuery before function:

<script>
    $(document).ready(function() {
        $("a.more-link").before("<button class=\"btn btn-default\">");
    }); 
</script>   

The output is:

<button class="btn btn-default"></button>
<a href="http://localhost/wordpress/post-2/#more-4" class="more-link">
    <span aria-label="Continue reading post 2">(more…)</span>
</a>

The following </button> tag is added automatically! Why? Can I not add a span between button tags? How can I prevent that or is there any way to add span between button tags?

$(document).ready(function() {
  $("a.more-link").before("<button class=\"btn btn-default\">");
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn btn-default"></button>
<a href="http://localhost/wordpress/post-2/#more-4" class="more-link">
    <span aria-label="Continue reading post 2">(more…)</span>
</a>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Mahsum Akbas
  • 1,523
  • 3
  • 21
  • 38

5 Answers5

1

You can't open a tag without close it that not a valid HTML, so the browser will always validate your HTML code by adding the closed tag.

If you want to wrap your span by button you could add it in your js using the jQuery method wrap() :

$( "a.more-link" ).wrap("<button class='btn btn-default'>");

NOTE : If you do so your HTML isn't valid since you shouldn't put an anchor a inside a button tag.

(PLEASE TAKE A LOOK TO Nesting <a> inside <button> doesn't work in Firefox).

Hope this helps.

$( "a.more-link" ).wrap("<button class='btn btn-default'/>");

console.log ( $('button')[0].outerHTML );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="http://localhost/wordpress/post-2/#more-4" class="more-link">My link </a>
Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

$(document).ready(function(){
    $( "a.more-link" ).before( "<button class=\"btn btn-default\"><span>I'm a span</span></button>" );
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://localhost/wordpress/post-2/#more-4" class="more-link">
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

zakaria is right you can't open a tag without closing it, wrap span within button, use this

$( "a.more-link span" ).wrap("<button class='btn btn-default'>");
iWasCloud
  • 107
  • 2
  • 13
-1

Use jquery wrap function.

<script>
    $(document).ready(function(){
       $( "a.more-link" ).wrap( "<button class=\"btn btn-default\">" );
    }); 
</script>   
VJAI
  • 32,167
  • 23
  • 102
  • 164
-1

I'm not sure what you exactly need, but try if wrap function is what you are looking for:

$( "a.more-link" ).wrap( "<button class=\"btn btn-default\">" )
malvarez
  • 276
  • 2
  • 13