I have on a webpage several buttons like that :
<div class="jet-portfolio__filter-item" data-slug="slug-one">
<div class="jet-portfolio__filter-item" data-slug="slug-two">
I'm catching a slug parameter passed in url that tells me which button I should click on page load. Question is how can I get the right button using javascript, since they don't have ids, to click it ?
Thanks !
You can do this very simple with the onclick JS function. Then you have two options for reading out the data element. 1) getAttribute() and 2) dataset
function myFn(elem) {
console.log('with getAttribute:', elem.getAttribute('data-slug'))
console.log('with dataset:', elem.dataset.slug)
}
<div class="jet-portfolio__filter-item" data-slug="slug-one" onclick="myFn(this)">click me! Slug One</div>
<div class="jet-portfolio__filter-item" data-slug="slug-two" onclick="myFn(this)">click me! Slug Two</div>
You've to use attribute selector to select those elements (assuming you're not using their classes to select them).
Here's the CSS attribute selector syntax: tag[attribute=value].
I think you can also replace tag with class or id but I'm not sure.
Now you can use this syntax in document.querySelector(selector).
const slugOne = document.querySelector("div[data-slug=slug-one]");
console.log(slugOne.innerText);
<div data-slug="slug-one">Content Of Slug One</div>
<div data-slug="slug-two">Content Of Slug Two</div>
You can select all elements by class name with "getElementByClassName" and then looping all elements and do addEventListenet to all selected items and pass a function to get the attribute of each element when the user does click.
var elements = document.getElementsByClassName("jet-portfolio__filter-item");
var onClickItems = function() {
var slug = this.getAttribute("data-slug");
console.log(slug)
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', onClickItems);
}
<div class="jet-portfolio__filter-item" data-slug="slug-one">Container number 1</div>
<div class="jet-portfolio__filter-item" data-slug="slug-two">Container number 2</div>