如何在基本Javascript中将“ img”标签添加到“ p”元素?

时间:2019-03-25 16:57:26

标签: javascript dom

因此,我试图在“ p”元素内添加“ img”标签。 但是,我似乎找不到如何设置“ img”标签属性。

我必须创建这个:

<p class="titre-recherche"><label>chaîne de caractères saisie</label><img src="croix30.jpg" class="icone-croix"/>value</p>

我尝试过: 创建具有不同属性的img元素并将其附加到“ p”元素上:

imgp = document.createElement("IMG")
imgp.setAttribute("src", "croix30.jpg")
imgp.setAttribute("class", "icone-croix")
divp.appendChild(imgp)

将img直接附加到原始节点上(这很丑):

document.getElementById("recherches-stockees").appendChild(divp).appendChild(imgp)

这是我的整个部分,并附有评论:

var saisie = document.getElementById('zone_saisie').value
// Create "p"
var divp = document.createElement("P")
// set "p" attributes
divp.setAttribute("class", "titre-recherche")
divp.setAttribute("label", "chaîne de caractères saisie")
// divp.setAttribute("img", "src=\"croix30.jpg\" class=\"icone-croix\"")
divp.setAttribute("img", "")
divp.getAttribute("img").setAttribute("src", "croix30.jpg")
.setAttribute("class", "icone-croix")
// Set "p" text
var t = document.createTextNode(saisie)
divp.appendChild(t)
// Create "img"
// imgp = document.createElement("IMG")
// Set "img" attributes
// imgp.setAttribute("src", "croix30.jpg")
// imgp.setAttribute("class", "icone-croix")
// Link "p" and "img"
// divp.appendChild(imgp)
document.getElementById("recherches-stockees").appendChild(divp)
// document.getElementById("recherches-stockees").appendChild(imgp)

最终输出应该是帖子开头给出的行。 预先感谢您的帮助,我希望这很清楚。

1 个答案:

答案 0 :(得分:2)

img元素不是属性,这就是使用setAttribute无效的原因。

您的代码是正确的方法:

imgp = document.createElement("IMG")
imgp.setAttribute("src", "croix30.jpg")
imgp.setAttribute("class", "icone-croix")
divp.appendChild(imgp)

也就是说,那些属性作为属性被反映为 ,因此:

imgp = document.createElement("IMG")
imgp.src = "croix30.jpg"
imgp.className = "icone-croix" // Note it's className, not class when it's a property
divp.appendChild(imgp)

在两种情况下,您都希望对label之前的img元素执行相同的操作。

或者,您可以使用insertAdjacentHTML

divp.insertAdjacentHTML("<label>chaîne de caractères saisie</label><img src='croix30.jpg' class='icone-croix'>")

或者因为您刚刚创建了divp并且其中没有其他内容,所以您可以分配给innerHTML

divp.innerHTML = "<label>chaîne de caractères saisie</label><img src='croix30.jpg' class='icone-croix'>"

(在上述所有情况下,您仍然需要document.getElementById("recherches-stockees").appendChild(divp)行。)