var geth4text = document.querySelector("#post > div > h4").innerHTML; var text = ""; var i; for (i = 0; i < geth4text.length; i++) { s = geth4text[i] text += "<li>"+s+"</li>"; } for (i = 0; i < geth4text.length; i++) { } document.getElementById("demo").innerHTML = text;
<div id="post"><div> <h4>Example 1</h4> <h4>Example 2</h4> <h4>Example 3</h4> <h4>Example 4</h4> <h4>Example 5</h4> </div></div> <span>Example</span> <div id="demo"></div>
This code outputs all characters from or h4 content
I am trying to extract the whole sum as it is in the first formula but within the " <li>
"
querySelector
returns the first element to match the query; querySelectorAll
, on the other hand, returns all elements that match the query.
However, querySelectorAll
returns an iterable but not an array, so we can use the [...querySelectorAll('')]
spread operator to construct an array of the elements.
var geth4text = [...document.querySelectorAll("#post > div > h4")].map(h4 => h4.innerText); var text = ""; var i; for (i = 0; i < geth4text.length; i++) { s = geth4text[i] text += "<li>" + s + "</li>"; } for (i = 0; i < geth4text.length; i++) { } document.getElementById("demo").innerHTML = text;
<div id="post"> <div> <h4>Example 1</h4> <h4>Example 2</h4> <h4>Example 3</h4> <h4>Example 4</h4> <h4>Example 5</h4> </div> </div> <span>Example</span> <div id="demo"></div>
Use createElement/appendChild instead of .innerHTML whenever you can to boost performance:
const list = document.getElementById('demo'); document.querySelectorAll('#post > div > h4').forEach(headline => { let listItem = document.createElement('li'); listItem.innerText = headline.innerText; list.appendChild(listItem); });
<div id="post"> <div> <h4>Example 1</h4> <h4>Example 2</h4> <h4>Example 3</h4> <h4>Example 4</h4> <h4>Example 5</h4> </div> </div> <span>Example</span> <ul id="demo"></ul>
You need to use querySelectorAll
rather than querySelector
as we are querying for multiple elements. querySelectorAll
returns a NodeList that (much like an array) exposes n forEach
method that we can use to iterate the elements. Also you should use document.appendChild
rather just setting innerHTML
( here's an explanation why ).
const demoEl = document.getElementById("demo"); document .querySelectorAll("#post > div > h4") .forEach( ({ innerHTML }) => (demoEl.appendChild(document.createElement("li")).innerHTML = innerHTML) );
<div id="post"> <div> <h4>Example 1</h4> <h4>Example 2</h4> <h4>Example 3</h4> <h4>Example 4</h4> <h4>Example 5</h4> </div> </div> <span>Example</span> <ul id="demo"></ul>
只需将#demo
的标签#demo
ul
而不是div
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.