Instantly share code, notes, and snippets.

Embed
What would you like to do?
Container Queries Mixin: Stylesheet version (using $this as a keyword for matching tags)
function containerQuery(selector, test, stylesheet) {
var tag = document.querySelectorAll(selector)
var style = ''
var count = 0
for (var i=0; i<tag.length; i++) {
var attr = (selector+test).replace(/\W+/g, '')
if (test(tag[i])) {
var css = stylesheet.replace(/:self|\$this/g, '[data-' + attr + '="' + count + '"]')
tag[i].setAttribute('data-' + attr, count)
style += css
count++
} else {
tag[i].setAttribute('data-' + attr, '')
}
}
return style
}
let containerQuery = (selector, test, stylesheet) => {
let style = ''
let count = 0
document.querySelectorAll(selector).forEach(tag => {
const attr = (selector+test).replace(/\W+/g, '')
if (test(tag)) {
const css = stylesheet.replace(/:self|\$this/g, `[data-${attr}="${count}"]`)
tag.setAttribute(`data-${attr}`, count)
style += css
count++
} else {
tag.setAttribute(`data-${attr}`, '')
}
})
return style
}
@VPenkov

This comment has been minimized.

Show comment
Hide comment
@VPenkov

VPenkov Nov 13, 2017

The ES5 version is a bit incorrect. Template literals are not an ES5 feature so the backticks need to go away.
In the ES6 version, I believe you don't ever change attr and css in the forEach call so they should be consts.

VPenkov commented Nov 13, 2017

The ES5 version is a bit incorrect. Template literals are not an ES5 feature so the backticks need to go away.
In the ES6 version, I believe you don't ever change attr and css in the forEach call so they should be consts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment