JavaScript按元素逐个字符获取样式。

huangapple go评论78阅读模式
英文:

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:

&lt;div id=&quot;my-div&quot;&gt;Hello &lt;b&gt;J&lt;/b&gt;oe&lt;/div&gt;

JavaScript:

console.log(document.getElementById(&quot;my-div&quot;).querySelectorAll(&quot;b&quot;));

Essentially, what you are doing is you are printing all the &lt;b&gt; 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:

&lt;div id=&quot;my-div&quot;&gt;&lt;i&gt;Hello&lt;/i&gt; &lt;b&gt;J&lt;/b&gt;oe&lt;/div&gt;

JavaScript:

console.log(document.getElementById(&quot;my-div&quot;).querySelectorAll(&quot;b&quot;), document.getElementById(&quot;my-div&quot;).querySelectorAll(&quot;i&quot;));

答案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(&quot;#testing&quot;).childNodes;
nodes.forEach(node =&gt; {
  console.log(node.textContent, node.nodeType === Node.ELEMENT_NODE, node.nodeName);
});

<!-- language: lang-html -->

&lt;div id=&quot;testing&quot;&gt;H&lt;b&gt;i&lt;/b&gt; I &lt;b&gt;a&lt;/b&gt;m b&lt;b&gt;o&lt;/b&gt;b&lt;/div&gt;

<!-- end snippet -->

so now to get the output

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const nodes = document.querySelector(&quot;#testing&quot;).childNodes;
const result = Array.from(nodes).flatMap(node =&gt; {
  const isElem = node.nodeType === Node.ELEMENT_NODE;  
  return Array.from(node.textContent).map(char =&gt; char === &#39; &#39; ? &#39;&#39; : `${char}: ${isElem}`);
});

console.log(result.join(&quot;\n&quot;));

<!-- language: lang-html -->

&lt;div id=&quot;testing&quot;&gt;H&lt;b&gt;i&lt;/b&gt; I &lt;b&gt;a&lt;/b&gt;m b&lt;b&gt;o&lt;/b&gt;b&lt;/div&gt;

<!-- end snippet -->

答案3

得分: 0

以下是已翻译的内容:

你可以迭代元素的子节点(递归)并累积字符与其父元素的映射关系。在收集了该列表之后,你可以对其进行映射,决定哪些类型的元素被视为“有样式”,并将其转换为布尔值。

这里是一个完整的示例,可以与你提供的输入一起使用。它还可以处理嵌套元素,并允许你修改哪些类型的元素被视为“有样式”:

TypeScript Playground中的代码

/** @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:

Code in TypeScript Playground

<!-- 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(&quot;Unexpected node type&quot;);
    }
  }
  return memo;
}

// Define which elemnet tag names are considered &quot;styled&quot;:
const styledElementTagNames = new Set([
  &quot;B&quot;,
  &quot;EM&quot;,
  &quot;I&quot;,
  &quot;STRONG&quot;,
  // etc.
]);

const targetElement = document.getElementById(&quot;testing&quot;);

const mapping = createTextMapping(targetElement);

const results = mapping
  .filter(([str]) =&gt; str.trim().length &gt; 0) // Remove whitespace
  .map(([str, elm]) =&gt; [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 -->

&lt;div id=&quot;testing&quot;&gt;H&lt;b&gt;i&lt;/b&gt; I &lt;b&gt;a&lt;/b&gt;m b&lt;b&gt;o&lt;/b&gt;b&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月14日 07:37:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定