0

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?

SanketR
  • 1,182
  • 14
  • 35

2 Answers2

1

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.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
0

Try using .find() to select img within .topStory parent element ; select parent of img element which is not .topStory ; select first element that is adjacent sibling to previously selected img parent element , call .text() on returned element

var topStory = $(".topStory");
var img = topStory.find("img");
// here `img.parents().not(topStory)` is `context`
var text = $("~ *:first", img.parents().not(topStory)).text();
console.log(img, text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>
jsfiddle http://jsfiddle.net/3cvh5rk5/
guest271314
  • 1
  • 15
  • 104
  • 177