Home > OS >  Selecting elements with querySelector
Selecting elements with querySelector

Time:01-06

<div id="~" 
    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;
};

I can now capture just the text within the strong tag. However, I cannot capture the data-relative attribute.

CodePudding user response:

You can use the querySelector method to find the strong element within the div, and then use the textContent property to get the text within it. You can better understand.

Try this:

      // 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);

You can use "for of" loop for all strong elements

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

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

CodePudding user response:

You can do it like this var element = document.querySelector(".list-header strong").textContent; to get the text inside the strong element inside your list-header class and var element2 = document.querySelector(".listview").getAttribute('data-relative'); to get the attribute

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

<div id="~"  data-identifier="~" data-relative="https://url_that_i_want_to_capture" data-feed="~">

CodePudding user response:

for the first question i'd suggest using

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

use .getAttribute("data-relative") to get the value of the attribute "data-relative"

or use .dataset.relative to get the value of the attribute "data-relative"

  • Related