Welcome to my blog!

Vòng lặp trong JavaScript

January 14, 2019 13:16

Vòng lặp trong JavaScript (edit)

  • HTMLCollection
  • NodeList
  • HTML DOM querySelector() Method
  • HTML DOM querySelectorAll() Method
  • document.getElementById('person'); //So sánh document.getElementById('person'); với elem.getElementById('person');
  • document.getElementsByTagName('*');
  • document.querySelector('*')
  • elem.getElementsByTagName(tag);
  • elem.getElementsByClassName(className);
  • elem.querySelectorAll(css);
  • elem.querySelector(css); //So sánh elem.querySelector(css); với elem.querySelectorAll(css)[0];
  • elem.closest(css);
  • elem.matches(css);
  • elem.closest(css);


  • document.getElementById
  • getElementsBy*
  • querySelectorAll
  • querySelector
  • matches
  • closest

Tham khảo




https://javascript.info/searching-elements-dom (Searching: getElement* and querySelector*)

Get the pure text without HTML element by javascript?

For loop for HTMLCollection elements


Mong muốn

Lấy được text trong dropdown

Giải pháp

var list = document.getElementsByTagName('li'); var startIndex = list.length - 16;var n = list.length; for (var i = startIndex; i < n; i++) { console.log(list[i].innerHTML.replace(/<[^>]*>/g, " ")); }

Kết quả


Một chương trình JavaScript đơn giản

<!doctype HTML>
.A {background: blue;}
.B {font-style: italic;}
.C {font-weight: bold;}
// my hacky approach:
function get_content() {
var html = document.getElementById("txt").innerHTML;
document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
// Gabi's elegant approach, but eliminating one unnecessary line of code:
function gabi_content() {
var element = document.getElementById('txt');
element.innerHTML = element.innerText || element.textContent;
// and exploiting the fact that IDs pollute the window namespace:
function txt_content() {
txt.innerHTML = txt.innerText || txt.textContent;
<a href="https://stackoverflow.com/questions/6743912/get-the-pure-text-without-html-element-by-javascript/">Get the pure text without HTML element by javascript?</a>
<input type="button" onclick="get_content()" value="Get Content (bad)"/>
<input type="button" onclick="gabi_content()" value="Get Content (good)"/>
<input type="button" onclick="txt_content()" value="Get Content (shortest)"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>


Recent posts