How to append content to querySelectorAll element with innerHTML/innerText?
Asked Answered
H

2

10

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?

Hispanicism answered 27/12, 2013 at 1:1 Comment(1)
document.querySelectorAll(".name")[0] -> you get a list and want the first itemHeterosexuality
H
21

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")
Heterosexuality answered 27/12, 2013 at 1:7 Comment(7)
Hi cocco, thanks a lot for your answer. For the single element selector: document.querySelector(".name"); - is it possible to refer to it more precise - like imagine I have class .name inside two different containers, one with id called: "name-container-1" the other "name-container-2"Hispanicism
you want to get an element by id?Heterosexuality
nope. I want to get it by classname, but I want to target the class name within a specific id containerHispanicism
i added a script on how you can get the individual id of every element.Heterosexuality
Ahh sry for not being precise - the scenario is: <div id="container1"><div class="my-class"></div></div>Hispanicism
But dont delete your latest example, that could come in handy :) Thanks so much for the effort - youve done more than needed.Hispanicism
The first edit (EDIT) for getting element by class and id saved me. Nice work!Gaylor
N
4

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);
Nolitta answered 30/1, 2019 at 6:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.