Using JQuery to get <h3> contents

14,096

The image doesn't have any siblings, do $(ec).siblings() is returning an empty set, and therefore .find("h3") doesn't find anything. The <h3> is a sibling of the image's parent <div>, so it should be:

var h3 = $(ec).parent().siblings("h3").text();

Or you could make it less dependent on the specific layout:

var h3 = $(ec).closest(".teaserBoxLink").find("h3").text();
Share:
14,096
Gaute
Author by

Gaute

Studying Information Science at the University of Bergen.

Updated on November 29, 2022

Comments

  • Gaute
    Gaute over 1 year

    I've working on trying to get the text inside a H3 tag for ages now, so I thought I would ask the community. I am using JQuery to get it, but I nothing returned when running the code.

    It may be better to show what I want:

    <a href="/eat-move-sleep/" class="teaserBoxLink _matchHeight">
      <div class="teaserBoxImage">
       <img src="/contentassets/6a53309d70054d14b988a9a45ab1c760/e43ee1c1d8ad4461802fde8ea7939a962.jpg?width=500&amp;height=200&amp;quality=90&amp;mode=crop" alt="" />
      </div>
      <h3 class="teaserBoxTitle">EAT MOVE SLEEP</h3>
    </a>
    

    I want to get the contents from the H3-tag (the text "EAT MOVE SLEEP") as the output.

    Here is a snippet of one of many ways I've tried:

    function(){
    var ec = {{Click Element}};
    var h3 = $(ec).siblings().find('h3').attr('class');
    return h3;
    }
    

    I am grateful for any help! :)

    • Barmar
      Barmar over 8 years
      Which element is Click Element?
    • Gaute
      Gaute over 8 years
      This is Google Tag Manager, so the click element refers to the image in this case :)
    • MinusFour
      MinusFour over 8 years
      Then the h3 tag is not a sibling of the clicking element, it's a sibling of the parent element. $(ec).parent().siblings('h3').text()