Search code examples
phpjqueryhtml-content-extraction

Find the text nearest to an element in HTML content


I have an HTML content with specific tags which have text and images in it. What if I am able to select an image and I want the the text nearest to an image?

<div class="topStory">
    <div class="photo">
    <a href="somelink"><img src="someimage.jpg" border="0" alt="Photo"></a>
    </div>
    <h2><a href="somelink">Text near to someimage.jpg</a></h2>
    <p>Some extra text.</p>
</div>

In this case I want the text nearest to someimage.jpg. Is it possible to achieve this using PHP? or may be jQuery?


Solution

  • With a minimum of DOM traversal you can select (click on) the image and find the text:

    <div class="topStory">
        <div class="photo">
        <a href="somelink"><img src="http://placehold.it/350x150" border="0" alt="Photo"></a>
        </div>
        <h2><a href="somelink">Text near to someimage.jpg</a></h2>
        <p>Some extra text.</p>
    </div>
    

    jQuery (get the sibling paragraph) UP to .photo and ACROSS to h2:

    $(document).on('click', 'img', function(e){
        e.preventDefault();
        var associatedText = $(this).closest('.photo').siblings('h2').text();
      console.log(associatedText);
    });
    

    You can also go further up the DOM if need be. UP to .topStory and DOWN to h2:

    $(document).on('click', 'img', function(e){
        e.preventDefault();
        var associatedText = $(this).closest('.topStory').find('h2').text();
      console.log(associatedText);
    });
    

    Here is the jQuery documentation for each function demonstrated:

    .closest()
    .siblings()
    .find()

    EDIT: Based on a good catch by @guest271314 and a re-reading of the OP's question, I have changed p to h2.