在HTML内容中查找最接近元素的文本


Find the text nearest to an element in HTML content

我有一个带有特定标签的HTML内容,其中包含文本和图像。如果我可以选择一个图像,并且我想要最接近图像的文本,该怎么办?

<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>

在这种情况下,我想要最接近someimage.jpg的文本。使用PHP可以实现这一点吗?或者可能是jQuery?

通过最少的DOM遍历,您可以选择(点击)图像并找到文本:

<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(获取同级段落)UP到.photo,ACROSS到h2:

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

如果需要,您也可以进一步向上访问DOM。向上到.topStory,向下到h2:

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

以下是演示的每个函数的jQuery文档:

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

编辑:根据@guest271314的一次精彩捕捉和对OP问题的重读,我将p更改为h2

尝试使用.find().topStory父元素中选择img;选择不是.topStoryimg元素的父元素;选择与先前选择的img父元素相邻的第一个元素,对返回的元素调用.text()

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>
jsfiddlehttp://jsfiddle.net/3cvh5rk5/