简体   繁体   中英

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?

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 .

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM