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

人走茶凉 提交于 2019-12-04 11:50:03

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")

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!