I hope the title is self-explanatory.
Basically I have the following code, and I wish to get the URL of the first image inside of my .content div so I can place it my header's og:image tag.
<div class="content">
<img src="image1.jpg">
<img src="image2.jpg">
</div>
For get the src
of first img
element from div and put that value in meta tag content, do something like this.
//getting div
var div = document.getElementsByClassName('content')[0];
//getting first img element and it's src from div
var firstImgSrc = div.getElementsByTagName('img')[0].src;
//creating meta tag, assigned image source to content and appending into head tag
var meta = document.createElement('meta');
meta.content = firstImgSrc;
document.getElementsByTagName('head')[0].appendChild(meta);
$('div.content > img:first-child').attr('src')
或$('div.content > img)[0].src
var firstImgUrl = $('.content img:first-of-type').attr('src');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.