如果div没有img标签,请向div添加“无图像”img(Javascript或Jquery)

时间:2013-03-21 07:57:48

标签: javascript jquery image prepend

如果div元素已经没有img标记,我正在尝试将img标记添加到div元素。什么是最好的使用方法?我想在javascript和jquery中看到答案,所以它会帮助我学习,但任何一个都没问题。

我使用.not()和.empty()进行了一些jquery尝试,但我觉得我没有正确思考它。

5 个答案:

答案 0 :(得分:3)

试试这个:

if($('#your_div').find('img').length==0){
   $('#your_div').prepend('<img src="img/your_image.jpg" />');
}

DEMO

答案 1 :(得分:3)

纯javascript并不像JQuery那样优雅

var imgexists = false;
for (var i = 0; i < mydiv.children.length; i++) {
    if (mydiv.children[i].tagName.toLowerCase() == "img") {
        imgexists = true;
        break;
    };
};

if (!imgexists) {
    var img = document.createElement("img");
    img.src = "some/path.png";
    if (mydiv.children.length > 0) {
        mydiv.appendChild(img, mydiv.firstChild);
    } else {
        mydiv.appendChild(img);
    };
};

答案 2 :(得分:3)

好的,你有很棒的jQuery解决方案,所以我建议使用纯JS版本:

var div = document.getElementById('div');

if (!div.querySelector('img')) {
    var img = document.createElement('img');
    img.src = 'image.png';
    div.insertBefore(img, div.firstChild);
}

测试:http://jsfiddle.net/9V2HR/

正如你所看到的,在这种情况下,vanilla JS几乎和jQuery代码一样短。

答案 3 :(得分:2)

if ($("#myId img").length === 0) {
    $("#myId").append("<img src=\"https://www.google.com/images/srpr/logo4w.png\" />");
}

Use jQuery length

不要使用纯JavaScript解决方案 - 它会不必要地复杂并且可能容易出现跨浏览器不兼容的情况

答案 4 :(得分:1)

使用lengthfind img标记...是prepend..no do other sttuff

使用jquery

if($('#divID').find('img').length > 0) {
   //img present so do other stuff 
}else{
   var img=$('<img />',{src:"imgsrc.jpg"});
  $('#divID').prepend(img)
};
相关问题