Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 341
user1231561 Avatar asked Dec 27 '13 01:12

user1231561


2 Answers

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")
like image 182
cocco Avatar answered Sep 17 '22 13:09

cocco


Easier solution, any use case. Query your selector:

let find = document.querySelector('.selector');

create some html as a string

let html = `put your html here`;

create element from string

  let div = document.createElement('div');
  div.innerHTML = html;

Append new html you created to selector

find.appendChild(div);
like image 27
chris_r Avatar answered Sep 19 '22 13:09

chris_r