json 使用querySelector选择元素

vktxenjb  于 2023-01-06  发布在  其他
关注(0)|答案(3)|浏览(164)
<div id="~" class="dm-post-0 well clearfix post listview"
    data-identifier="~" data-relative="https://url_that_i_want_to_capture"
    data-feed="~">

let convertEntries = () => {
  "use strict";
  let target = [...document.getElementsByClassName("listview")];
  let result = [];
  target.forEach((element) => {
    result.push({
      title: element.querySelector(".list-header strong").textContent,
      url: element.querySelector("#listview").dataset.relative,
    });
  });
  return result;
};

我现在只能捕获strong标记中的文本,但是不能捕获data-relative属性。

soat7uwm

soat7uwm1#

可以使用querySelector方法在div中找到strong元素,然后使用textContent属性获取其中的文本,这样可以更好地理解。
试试这个:

// Get the div element
      const div = document.querySelector("div.pull-left.list-header");

      // Get the strong element within the div
      const strong = div.querySelector("strong");

      // Get the text within the strong element
      const text = strong.textContent;
      console.log(text);

可以对所有强元素使用"for of"循环

const strongs = document.querySelectorAll("div.list-header > strong");

      for (const strong of strongs) {
        const text = strong.textContent;
        console.log(text);
      }
9o685dep

9o685dep2#

您可以像这样执行var element = document.querySelector(".list-header strong").textContent;以获取list-header类中strong元素内的文本,并执行var element2 = document.querySelector(".listview").getAttribute('data-relative');以获取属性

var element = document.querySelector(".list-header strong").textContent;
var element2 = document.querySelector(".listview").getAttribute('data-relative');
console.log(element);
console.log(element2);
<div class="pull-left list-header" dir="ltr">
  <strong>[Text that I want to capture</strong>
  <span> - [Text that I want to exclude]</span>
</div>

<div id="~" class="dm-post-0 well clearfix post listview" data-identifier="~" data-relative="https://url_that_i_want_to_capture" data-feed="~">
92dk7w1h

92dk7w1h3#

对于第一个问题,我建议使用

document.querySelector(".list-header strong").textContent;

使用.getAttribute("data-relative")获取属性"data-relative"的值
或使用.dataset.relative获取属性"data-relative"的值

相关问题