1

I'm trying to pull a link from the following html. There's lots of bits of HTML like this one in an array.

tweets[0] is:

var tweets = Array.from(document.querySelectorAll("[class ^= AdaptiveMedia-ph]"));
console.log(tweets);
<div class="AdaptiveMedia-photoContainer js-adaptive-photo " data-image-url="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" data-element-context="platform_photo_card" style="background-color:rgba(51,64,18,1.0);" data-dominant-color="[51,64,18]">
  <img data-aria-label-part="" src="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" alt="A tree" style="width: 100%; top: -0px;">
</div>

How do I go about actually pulling the link in "src" and the alt text from "alt" from the HTML text? Thanks in advance!

2
  • You mean the src and alt from the inner <img> tag? Commented Jun 7, 2018 at 12:54
  • Why use the Array.from() ?? Can we remove this? Commented Jun 7, 2018 at 12:56

2 Answers 2

2

Like this:

var tweets = document.querySelectorAll("[class ^= AdaptiveMedia-ph]");
for (var i=0;i<tweets.length;i++) {
  console.log("data-image-url",tweets[i].getAttribute("data-image-url"));
  var img = tweets[i].querySelector("img");
  console.log("image-url",img.src,"alt",img.alt);
  
}
<div class="AdaptiveMedia-photoContainer js-adaptive-photo " data-image-url="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" data-element-context="platform_photo_card" style="background-color:rgba(51,64,18,1.0);" data-dominant-color="[51,64,18]">
  <img data-aria-label-part="" src="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" alt="A tree" style="width: 100%; top: -0px;">
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

Would be easier if you would select directly the img elements and then just .map() the results:

// Select img inside the cards
var tweets = Array.from(document.querySelectorAll("[class ^= AdaptiveMedia-ph] img"));

var imgData = tweets.map(e => ({src: e.src, alt: e.alt}));
console.log(imgData);
<div class="AdaptiveMedia-photoContainer js-adaptive-photo " data-image-url="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" data-element-context="platform_photo_card" style="background-color:rgba(51,64,18,1.0);" data-dominant-color="[51,64,18]">
  <img data-aria-label-part="" src="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" alt="A tree" style="width: 100%; top: -0px;">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.