How to append content to querySelectorAll element with innerHTML/innerText?

user1231561 picture user1231561 · Dec 27, 2013 · Viewed 39.2k times · Source

I currently have my class element:

var frame_2 = document.querySelectorAll(".name");

Currently this div is empty. I now want to "append/add" some content to that div - I had a go with innerHTML + innerText but for some reason nothing seems to be added.

Example:

frame_2.innerHTML = '<img src="image.gif" />';

and

frame_2.innerText = 'some text';

Any suggestions? Im not sure if there are ways of doing the same - or performance'wise something better?

Answer

cocco picture cocco · Dec 27, 2013

this gives you a list of elements that contain the class name

var name=document.querySelectorAll(".name");

you want the first element?

name[0].textContent='some text';

This gives you one single element, the first one.

var name=document.querySelector(".name");
name.textContent='some text';

To append stuff

name.appendChild(document.createTextNode('pizza'));
name.appendChild(document.createElement('div')).textContent='spaghetti';
name.appendChild(document.createElement('img')).src='cookie.jpg';

EDIT

To get the elements by classname, then retrieve the id :

var names=document.querySelectorAll(".name"),l;
while(l--){
console.log(names[l].id);
}

or if i didn't understand correctly

html

<div class="spaghetti" id="pizza"></div>

js

document.querySelector(".spaghetti#pizza")

EDIT2

html

<div id="container1"><div class="my-class"></div></div>

js

document.querySelector("#container1>.my-class")