英文:
Javascript get style character by character in an element
问题
我有一个动态创建的包含样式字符的 div,例如:
<div>Hello <b>J</b>oe</div>
我正在尝试弄清楚哪些字符具有样式(在这种情况下是 J)。
我已经尝试过 window.getComputedStyle()
,但未能逐个获取样式字符。
更大的示例:
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
预期输出:
getDivStyle("testing") =>
H: false
i: true
I: false
a: true
m: false
B: false
o: true
b: false
谢谢你的帮助!
英文:
I have a dynamically created div with styled characters such as:
<div>Hello <b>J</b>oe</div>
and I am trying to figure out which characters are styled (in this case the J).
I have already tried window.getComputedStyle()
but I was unsuccessful in getting the style character by character.
Bigger example:
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
Expected output:
getDivStyle("testing") =>
H: false
i: true
I: false
a: true
m: false
B: false
o: true
b: false
Thank you for your help!
答案1
得分: 1
HTML:
<div id="my-div">Hello <b>J</b>oe</div>
JavaScript:
console.log(document.getElementById("my-div").querySelectorAll("b"));
HTML:
<div id="my-div"><i>Hello</i> <b>J</b>oe</div>
JavaScript:
console.log(document.getElementById("my-div").querySelectorAll("b"), document.getElementById("my-div").querySelectorAll("i"));
英文:
If it is only bolded elements, you could do this:
HTML:
<div id="my-div">Hello <b>J</b>oe</div>
JavaScript:
console.log(document.getElementById("my-div").querySelectorAll("b"));
Essentially, what you are doing is you are printing all the <b>
elements in the div
.
<br>
However, the above applies to only bolded elements. If you would like to do it with more than just bolded elements, you can do this, but you need to know ALL the element tags. Like so:
HTML:
<div id="my-div"><i>Hello</i> <b>J</b>oe</div>
JavaScript:
console.log(document.getElementById("my-div").querySelectorAll("b"), document.getElementById("my-div").querySelectorAll("i"));
答案2
得分: 1
读取子节点,您可以查看文本、类型和节点值。您可以轻松地按字符拆分它以获取输出。
const nodes = document.querySelector("#testing").childNodes;
nodes.forEach(node => {
console.log(node.textContent, node.nodeType === Node.ELEMENT_NODE, node.nodeName);
});
现在要获取输出:
const nodes = document.querySelector("#testing").childNodes;
const result = Array.from(nodes).flatMap(node => {
const isElem = node.nodeType === Node.ELEMENT_NODE;
return Array.from(node.textContent).map(char => char === ' ' ? '' : `${char}: ${isElem}`);
});
console.log(result.join("\n"));
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
英文:
Read the child nodes and you can look at the text, type, and node value. You can easily split it on characters to get the output.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const nodes = document.querySelector("#testing").childNodes;
nodes.forEach(node => {
console.log(node.textContent, node.nodeType === Node.ELEMENT_NODE, node.nodeName);
});
<!-- language: lang-html -->
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
<!-- end snippet -->
so now to get the output
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const nodes = document.querySelector("#testing").childNodes;
const result = Array.from(nodes).flatMap(node => {
const isElem = node.nodeType === Node.ELEMENT_NODE;
return Array.from(node.textContent).map(char => char === ' ' ? '' : `${char}: ${isElem}`);
});
console.log(result.join("\n"));
<!-- language: lang-html -->
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
<!-- end snippet -->
答案3
得分: 0
以下是已翻译的内容:
你可以迭代元素的子节点(递归)并累积字符与其父元素的映射关系。在收集了该列表之后,你可以对其进行映射,决定哪些类型的元素被视为“有样式”,并将其转换为布尔值。
这里是一个完整的示例,可以与你提供的输入一起使用。它还可以处理嵌套元素,并允许你修改哪些类型的元素被视为“有样式”:
/** @returns an array of [character, parent element] */
function createTextMapping(element, memo = []) {
for (const node of element.childNodes) {
switch (node.nodeType) {
case Node.TEXT_NODE: {
for (const str of node.data) {
memo.push([str, element]);
}
break;
}
case Node.ELEMENT_NODE: {
createTextMapping(node, memo);
break;
}
default: throw new Error("Unexpected node type");
}
}
return memo;
}
// 定义哪些元素标签名称被视为“有样式”:
const styledElementTagNames = new Set([
"B",
"EM",
"I",
"STRONG",
// 等等。
]);
const targetElement = document.getElementById("testing");
const mapping = createTextMapping(targetElement);
const results = mapping
.filter(([str]) => str.trim().length > 0) // 移除空白字符
.map(([str, elm]) => [str, styledElementTagNames.has(elm.tagName)]); // 验证父元素
for (const [str, valid] of results) {
console.log(`${str}:`, valid);
}
body { font-family: sans-serif; }
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
英文:
You can iterate the element's child nodes (recursively) and accumulate a mapping of the characters to their parent elements. After collecting that list, you can map over it, deciding which types of elements are considered "styled", and convert those to boolean values.
Here's a complete example that will work with the input you showed. It will also work with nested elements and it will allow you to modify which types of elements are the "styled" ones:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
/** @returns an array of [character, parent element] */
function createTextMapping(element, memo = []) {
for (const node of element.childNodes) {
switch (node.nodeType) {
case Node.TEXT_NODE: {
for (const str of node.data) {
memo.push([str, element]);
}
break;
}
case Node.ELEMENT_NODE: {
createTextMapping(node, memo);
break;
}
default: throw new Error("Unexpected node type");
}
}
return memo;
}
// Define which elemnet tag names are considered "styled":
const styledElementTagNames = new Set([
"B",
"EM",
"I",
"STRONG",
// etc.
]);
const targetElement = document.getElementById("testing");
const mapping = createTextMapping(targetElement);
const results = mapping
.filter(([str]) => str.trim().length > 0) // Remove whitespace
.map(([str, elm]) => [str, styledElementTagNames.has(elm.tagName)]); // Validate parent elements
for (const [str, valid] of results) {
console.log(`${str}:`, valid);
}
<!-- language: lang-css -->
body { font-family: sans-serif; }
<!-- language: lang-html -->
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论