我正在嘗試獲取標簽的innerHTMLor value(取決于標簽),但不確定如何回圈嵌套的子標簽。當標簽中只包含“World”時,我希望將樣式應用于標簽。這是小提琴鏈接。smb 能幫忙嗎?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Iterave over Children of HTML Element using JavaScript</h2>
<div id="myElement">
<p>Hello <span>World</span>!</p>
<ul>
<li>List Item</li>
</ul>
<div>
Sample World
<div>
Nested Div
<div>
Another Nested Div with World
</div>
</div>
</div>
</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<p id="out"></p>
<script>
function execute(){
var element = document.getElementById("myElement");
var children = element.children;
for(var i=0; i<children.length; i ){
var child = children[i];
console.log(child)
if (child.innerHTML.includes("World"))
child.style.color = "red";
}
}
</script>
</body>
</html>
uj5u.com熱心網友回復:
該解決方案是在我看來相當untrivial,既innerHtml和innerText回傳所有子節點的文字也是如此。首先,我會做一個遞回解決方案 - 查看所有這些子節點。因為我們只需要父節點的文本 - 我們必須洗掉節點的所有子節點。我們必須在不改變 DOM 的情況下做到這一點 - 克隆元素將在這里解決。當涉及到父節點樣式也應用于子節點時,會出現第三個問題 - 我將使用一個幫助器 css 類來保持文本為黑色。
function recursive_execute(el){
var element; //out target element
if(!el){ //if nothing is passed to function we take the root: `myElement`
element = document.getElementById("myElement");
}
else{
element = el;
}
var children = element.children;
if(children.length > 0){
for(let i = 0; i < children.length; i ){
let child = children[i];
recursive_execute(child); //call function for all children of the target element
}
}
let item = element.cloneNode(true); //cloning target node
if(item.children && item.children.length > 0){
for(let i = 0; i < item.children.length; i ){
let child = item.children[i];
if(child.tagName){ //getting rid of children who are tagged (so we don't get rid of text)
item.removeChild(child);
}
}
}
if(item.innerHTML && item.innerHTML.includes("World")){ //check if our clone contains the desired word
element.style.color = "red"
}else{
element.className = "helper" //if not - assigning helper class
}
}
.helper{
color:black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Iterave over Children of HTML Element using JavaScript</h2>
<div id="myElement">
<p>Hello <span>World</span>!</p>
<ul>
<li>List Item</li>
</ul>
<div>
Sample World
<div>
Nested Div
<div>
Another Nested Div with World
</div>
</div>
</div>
</div>
<br>
<button type="button" onclick="recursive_execute()">Click Me</button>
<p id="out"></p>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327698.html
標籤:javascript dom
上一篇:如何在div中創建div?
