How to copy and alert an child element

Viewed 34

$('h1').click(function(){
    var span = $(this).find('.secondary');
    alert(span);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
    Hello 
    <span class='secondary'>World</span>
</h1>

How to i copy the entire .secondary element and alert it like this

<span class='secondary'>World</span>

3 Answers

There's a few problems with your solution:

  1. alert the span's outerHTML instead of just the JQuery span object.
  2. .secondary instead of secondary for your selector (the . indicates that it's a class, read more here).
  3. Use $(document).ready() This will make sure that JQuery is loaded and ready to be used, and that all the elements are loaded before running any JQuery.

In the end, with all these problems solved, your code should look like this:

$(document).ready(function () {
    $('h1').click(function () {
        var span = $(this).find('.secondary');
        alert(span[0].outerHTML);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
    Hello 
    <span class='secondary'>World</span>
</h1>

What you want is the outer HTML of the currently selected element. There is no direct function for this in jQuery, so you need to:

  1. first wrap it in another element,
  2. then go upward to that wrapper element
  3. now you can use html() to get inner html of this wrapper element, which is actually the outer html for your original element.

You can use jQuery's clone() method to create a copy and perform the manipulations on that clone element, thus keeping your original element as it is.

$('h1').click(function(){
    var span = $(this).find('.secondary').clone().wrap('<p>').parent().html();
    alert(span);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
    Hello 
    <span class='secondary'>World</span>
</h1>

To then grab the html element as a string you would do:

document.documentElement.outerHTML

    <script>
        $('h1').click(function () {
            var span = document.find('secondary').outerHTML;
            alert(span);
        })
    </script>
Related