简体   繁体   中英

Fetching “id” from first 5 tags and separate them with comma in output using pure javascript

I am working on one of script where I need to pull the value available in id on tag I need to use pure Javascript to get this done. I have similar jQuery code available but I am not able to successfully complete Javascript one. My jquery Code

var arr1st3 = $('article:lt(3)').map(function() {
    return this.id.replace(/[^\d]/g, '');
}).get();
console.log( arr1st3 );

Here is the test url http://jsfiddle.net/0mvjbkhs/5/

I am trying to have Javascript function that will return the values in output like ['123456', '7896669', '1147777']

Any help will be really appreciated

Pure javascript version would be:

var arr2st3 = [].map.call(document.querySelectorAll('article:nth-child(-n+4)'), function(el) {
    return el.id.replace(/[^\d]/g, '');
});

Quite similar. You just use native Array.prototype.map and article:nth-child(-n+4) CSS selector to select elements.

Demo: http://jsfiddle.net/0mvjbkhs/6/

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.

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