简体   繁体   English

Javascript-从DIV的内部HTML中提取所有标题

[英]Javascript - Extract all Title from inner HTML of a DIV

How to extract particular properties from inner HTML in a complete div. 如何在完整的div中从内部HTML中提取特定属性。

For Ex - I have 对于前-我有

[Check the image, I have highlighted the part I want to extract][1]

I want to extract only the last 5 digits number from every ALT="Blah, blah... , 87876 " inside the blue highlighted div 我只想从蓝色突出显示的div内的每个ALT =“ Blah,blah ...,87876”中仅提取最后5位数字

After that i want to put all the values in an array with comma seperated and remove all duplicates. 之后,我想将所有值放入逗号分隔的数组中,并删除所有重复项。

      var Array = [];

    // solution code

        var values = Array.join(", ");

    alert (values);

// shows up "34322, 23215, 52334, ....., 34123"

Please explain with an example respective to my problem mentioned above. 请举例说明上述问题。

Your picture didn't show up, but it's easy enough to get the number: 您的照片没有出现,但很容易获得编号:

var example = "Blah, blah... , 87876 ";
example.trim().match(/[\d]+$/g)

You can use querySelectorAll to get all elements with an alt attribute: 您可以使用querySelectorAll获取具有alt属性的所有元素:

document.querySelectorAll('.tab-content *[alt]')

Combine these ideas with Array.reduce and you can build a list of all the numbers: 将这些想法与Array.reduce结合使用,您可以构建所有数字的列表:

Array.from(document.querySelectorAll('.tab-content *[alt]')).reduce((acc, el) => {
   const match = el.getAttribute('alt').trim().match(/[\d]+$/g);
   if (match) { return acc.concat(match); }
   return acc;
}, []);

Here is a non-es6 version: 这是非es6版本:

var elements = [].slice.call(document.querySelectorAll('.tab-content *[alt]'), 0);
elements.reduce(function(acc, el) {
   const match = el.getAttribute('alt').trim().match(/[\d]+$/g);
   if (match) { return acc.concat(match); }
   return acc;
}, []);

Removing duplicates is easy with es6: 使用es6可以轻松删除重复项:

const altNums = Array.from(document.querySelectorAll('.tab-content *[alt]')).reduce((acc, el) => {
   const match = el.getAttribute('alt').trim().match(/[\d]+$/g);
   if (match) { return acc.concat(match); }
   return acc;
}, []);
const unique = [...new Set(altNums)];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM