adam78
adam78

Reputation: 10068

jQuery to get value of child HTML element

How can I get the text inside the h4 tag with class .media-heading in the following example when a person clicks on the link. I've tried using the closest method and it doesn't seem to work. see below:

<li class="media ">
    <a href="example.com" class="external" >
        <div class="media-left">
            ...
        </div>
        <div class="media-body">
            <h4 class="media-heading">An Extertnal Website</h4>
        </div>
    </a>
</li>

<div class="modal " id="extLinkModal" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="extLinkModalLabel"></h4>
            </div>
            <div class="modal-body">
                <iframe name="myiframe" id="myiframe" frameborder="0"   width="100%" height="100%" ></iframe>
            </div>
        </div>
    </div>
</div>
$('a.external').on('click', function(e) {
    e.preventDefault();
    var src = $(this).attr('href');
    var title = $(this).closest('.media-heading').text();

    $('#extLinkModal').modal('show');
    $('#extLinkModal .modal-title').html( title );
    $('#extLinkModal iframe').attr('src', src);
});

Upvotes: 2

Views: 1679

Answers (2)

Quỳnh MSO
Quỳnh MSO

Reputation: 66

Use Jquery

$(".media-heading").text()

-Function

$('a.external').on('click', function(e) {
   alert($(".media-heading").text());
    $(".modal-title").text($(".media-heading").text());
});

<li class="media ">
    <a href="#" class="external" >
        <div class="media-left">
            ...
        </div>
        <div class="media-body">
            <h4 class="media-heading">An Extertnal Website</h4>
        </div>
    </a>
</li>

<div class="modal " id="extLinkModal" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="extLinkModalLabel"></h4>
            </div>
            <div class="modal-body">
                <iframe name="myiframe" id="myiframe" frameborder="0"   width="100%" height="100%" ></iframe>
            </div>
        </div>
    </div>
</div> 

http://jsfiddle.net/98f3psLv/6/

if you want to get from parent element:

$(".external .media-body .media-heading").text()

if you want to get from $this

$(this).find(".media-heading").text()

Upvotes: 0

Jai
Jai

Reputation: 74738

instead of .closest():

$(this).closest('.media-heading').text();

use .find():

$(this).find('.media-heading').text();

.closest():

It traverses back to parent element provided as a string whether that is id/class/tagname/"[attribute/s].

.find():

It gets the deep child id/class/tagname/[attribute/s].

Upvotes: 4

Related Questions