如何使用javascript或jquery获取某些DOM元素后的第一个图像标记?

时间:2014-04-07 14:15:38

标签: javascript jquery html

让我说我的代码就像。

<h1>Big heading</h1>
<p>small heading</p>
<img src="image.com"/>
.........

如何使用javascript或jquery在img之后获取第一个<h1>标记?

5 个答案:

答案 0 :(得分:1)

试试这个

$('h1').nextAll('img').first();

快乐编码:)

答案 1 :(得分:1)

您可以使用nextUntil(),然后next()来获取下一个元素,即图像

$('h1').nextUntil('img').last().next()

nextAll()然后first()

$('h1').nextAll('img').first()

答案 2 :(得分:1)

如果您想要任何 h1元素之后的第一个后续图片元素,则可以将next siblings selector (~):first selector结合使用:

$('h1 ~ img:first')

如果您想要每个 h1元素之后的第一个后续图像元素,那么您将要使用更高级的选择:

var $imgs = $();
$('h1').each(function () {
    $img = $(this).nextAll('img').first();
    $imgs = $imgs.add($img);
});

demo

使用原始JS执行相同搜索的代码要多得多,但是它的性能更高,因为我们可以进行一些可以减少迭代次数的优化:

function firstImagesAfterHeadings() {
    "use strict";
    var nodeName,
        headings,
        images,
        image,
        ctx,
        i;

    //get all the headings on the page
    headings = document.getElementsByTagName('h1');

    //create a container for the images that are selected
    images = [];

    //iterate through all the headings
    for (i = 0; i < headings.length; i += 1) {
        //start at the heading
        ctx = headings[i];

        //clear out any existing selected images
        image = null;

        //walk through each of the headings' siblings
        //the assignment here is intentional,
        //the second set of parenthesis is used to acknowledge this
        //additionally, the "outer" label is used so that breaking
        //out of the switch also breaks out of the loop
        outer:while ( (ctx = ctx.nextSibling) ) {
            //normalize the node name
            nodeName = ctx.nodeName.toLowerCase();

            switch (nodeName) {
                //the first image found after the heading should
                //be added to the collection
                case 'img':
                    image = ctx;
                    break outer;
                //any headings found after the initial heading should break
                //because they will have been in the headings collection and
                //will be used as a search context on the next iteration of
                // the for loop
                case 'h1':
                    break outer;
            }
        }

        //it's possible that an image is never found,
        //or that a heading is found first
        if (image) {
            images.push(image);
        }
    }
    return images;
}

demo

答案 3 :(得分:0)

 use the following line to check the img:

  $('h1').nextAll('img:first');

答案 4 :(得分:-1)

在这里你可以使用纯javaScript,如: -

这将提供第一个h1代码

的第一张图片
var h1Tag = document.getElementsByTagName('h1')[0];
var imgTags = h1Tag.getElementsByTagName('img');
var firstImg = imgTags[0]; //provide the first img after h1 tag