Get attribute from a specific element of a class

Related searches

Basically I have to develop a Tic-Tac-Toe game, here is the HTML file which I can't rewrite only reformat a bit, but the idea should stay the same.

{% block content %}
    <nav class="navbar fixed-top navbar-light">
        <button id="retry-button" class="btn btn-success">Try again?</button>
        <a href="/" class="btn btn-outline-dark">Reset settings</a>
    </nav>
    <div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
        {% for row in range(row_num) %}
            <div>
                {% for col in range(col_num) %}
                    <div class="game-cell"
                         data-coordinate-x="{{ col }}"
                         data-coordinate-y="{{ row }}"></div>
                {% endfor %}
            </div>
        {% endfor %}
    </div>
{% endblock %}

As you can see i have a game-cell class which contains by default 9 elements. I would like to return the data-coordinate-x and data-coordinate-y when I click one of the game-cells. I had a previous try but if I clicked it returned all of the blocks not just the one i clicked on. I have to write it in Js. If you can point me in the right direction that's more than enough for me. Thanks!

If I understood correctly, you need to access data attributes of your game-cell element. In order to do this, you need to select the element by some ID or class. I have modified your code a little to make it run inside stackoverflow`s platform. I have added an ID which i called "unique" and I also set some values into your coordinate-x and y data attributes. Please review the code bellow and see how I managed to get those data attributes. It's important to notice that this is not the only way to access them.

var gamecell = document.getElementById('unique');
 
console.log(gamecell.dataset.coordinateX);
console.log(gamecell.dataset.coordinateY);
<nav class="navbar fixed-top navbar-light">
        <button id="retry-button" class="btn btn-success">Try again?</button>
        <a href="/" class="btn btn-outline-dark">Reset settings</a>
    </nav>
    <div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
            <div>
                    <div class="game-cell" id="unique"
                         data-coordinate-x="172"
                         data-coordinate-y="273"></div>
            </div>
    </div>

Element.getAttribute(), If I understood correctly, you need to access data attributes of your game-cell element. In order to do this, you need to select the element by� The getAttribute() method returns the value of the attribute with the specified name, of an element. Tip: Use the getAttributeNode() method if you want to return the attribute as an Attr object. Browser Support

Simply access your clicked game-cell by: (it will find the clicked coordinateX and coordinateY)

document.querySelectorAll('.game-cell').forEach((game) => {
   game.addEventListener('click',function(event){
   console.log(game.dataset.coordinateX);
   console.log(game.dataset.coordinateY);
  });
});

Get attribute from a specific element of a class, For element nodes, most standard HTML attributes automatically that belong to a built-in Attr class, with name and value properties. getAttribute('About') – the first letter is uppercase here, and in HTML it's all lowercase. The [attribute^="value"] selector is used to select elements whose attribute value begins with a specified value. The following example selects all elements with a class attribute value that begins with "top": Note: The value does not have to be a whole word!

you must to get your element by class name or id(add an id) than you can get its attributes like this

let gameCell = document.getElementById('game-cell-id');// id for example
gameCell.getAttribute('data-coordinate-x')

Attributes and properties, The getAttribute() method is used to get the current value of a attribute on the element. If the specified attribute does not exist on the element, it will return null . example will add a class and a disabled attribute to the <button> element. The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as an HTMLCollection object. The HTMLCollection object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

JavaScript DOM Get Set Attributes, Using jQuery's .attr() method to get the value of an element's attribute has two main The difference between attributes and properties can be important in specific WARNING: When setting the 'class' attribute, you must always use quotes! public boolean elementHasClass(WebElement element, String active) { return element.getAttribute("class").contains(active); } This approach looks simpler but has one big caveat: As pointed out by @JuanMendes you will run into problems if the class-name you're searching for is a substring of other class-names:

.attr(), Classes are used by CSS and JavaScript to select and access specific elements; The class attribute can be used on any HTML element; The class name is case sensitive; Different HTML elements can point to the same class name; JavaScript can access elements with a specific class name with the getElementsByClassName() method

The getElementsByClassName () method returns a collection of an element's child elements with the specified class name, as a NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Comments
  • have you tried giving it an onclick attribute to the game cell ? Something like onclick="returnCoord(this)" and getting your coord from the "this" in js ?
  • Yeah I know it is possible that way, the thing is we are learning DOM manipulation and I tought it's better to implement it in pure javascript. And after getting the attributes it would be nice to know the exact element because i have to change it a few times, but only the clicked one
  • What you posted is not HTML. Please post the rendered HTML in a minimal reproducible example with the JS you have written so far
  • I think I will go with Antonie553's idea, but thanks for helping me out!
  • It is CLASS game-cell and that is a collection