Using jQuery and CSS to showcase a unique attribute of a div element

I am an amateur coder with a question that has been puzzling me for some time now. I have a feeling it should be simple, but I just can't seem to figure it out on my own. Maybe I haven't been looking in the right places... I hope you can provide some assistance.

On a page, I have a series of <div> elements with various custom attributes. Here is an example:

<div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain" 
     playerposition="0" style="position: absolute; left: 772.632px; top: 215.934px; 
     width: 46.5668px; height: 46.5789px; color: rgb(255, 255, 255);
     background-color: rgb(255, 0, 0);"></div>

How can I use CSS to display the "rownumber" attribute for all <div> elements with the class 'face' initially.... and then change it to display "playername" for all elements after clicking on one button.... and finally, display "playerrole" after clicking on another button?

Thank you for taking the time to read this. I look forward to your response.

Answer №1

Sure thing! The functionality is achieved by adjusting the class on the 'selected' element and using CSS to display different values depending on the class.

$('.selector').click(function(){
  $('#selected').attr('class',$(this).text());
});
.rownumber .face:after { content: attr(rownumber); }
.playername .face:after { content: attr(playername); }
.playerrole .face:after { content: attr(playerrole); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='selected' class='rownumber'>
<div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain" 
     playerposition="0" style="position: absolute; left: 772.632px; top: 215.934px; 
     width: 46.5668px; height: 46.5789px; color: rgb(255, 255, 255);
     background-color: rgb(255, 0, 0);"></div>
 </div>
<button class='selector'>rownumber</button>
<button class='selector'>playername</button>
<button class='selector'>playerrole</button>

An alternative pure CSS solution would look like this:

[name=selected][value=rownumber]:checked ~ div .face:after {
  content: attr(rownumber);
}
[name=selected][value=playername]:checked ~ div .face:after {
  content: attr(playername);
}
[name=selected][value=playerrole]:checked ~ div .face:after {
  content: attr(playerrole);
}
<input type='radio' name='selected' value='rownumber'>Rownumber
<input type='radio' name='selected' value='playername'>Playername
<input type='radio' name='selected' value='playerrole'>Playerrole
<div>
  <div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain" playerposition="0" style="position: absolute; left: 772.632px; top: 215.934px; 
     width: 46.5668px; height: 46.5789px; color: rgb(255, 255, 255);
     background-color: rgb(255, 0, 0);"></div>
</div>

Answer №2

Implementing jQuery and utilizing the .attr( attributeName) method to extract attribute values, then employing jQuery once more to seamlessly insert that text (the extracted attribute value) where required.

Answer №3

$(document).ready(function(){
  $(".face").each(function(){
    var rowNumber = $(this).attr('rownumber');
    $(this).text(rowNumber);
  });
});

$("#pn").click(function(){
  $(".face").each(function(){
    var playerName = $(this).attr('playername');
    $(this).text(playerName);
  });
});

$("#pr").click(function(){
  $(".face").each(function(){
    var playerRole = $(this).attr('playerrole');
    $(this).text(playerRole);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain" playerposition="0"></div>

<div class="face" rownumber="2" rowposition="0" playername="Rob krest" playerrole="Pirate" playerposition="0"></div>

<div class="face" rownumber="3" rowposition="0" playername="Alex Konst" playerrole="Cyborg" playerposition="0"></div>

<button id="pn">Display Player Name</button>
<button id="pr">Show Player Role</button>

Answer №4

One idea to consider is utilizing the data- attributes for your work.

Take a look at this demonstration: https://jsfiddle.net/1fbLm2sg/

I've included some buttons that will insert the values of the various div data- attributes into the node itself.

<div class="person" data-id="1" data-name="John Doe" data-role="Manager" style=" width: 50px; height: 50px; color: #FFF; background-color: rgb(0, 128, 255);">Person 1</div>
<div class="person" data-id="2" data-name="Jane Smith" data-role="CEO" style="width: 60px; height: 60px; color: #000; background-color: rgb(255, 0, 0);">Person 2</div>
<button class="get-id">Show ID</button>
<button class="get-name">Show Name</button>

Here's the corresponding JavaScript code:

$('.get-id').click(function() {  
   $('.person').each(function() {  
      $(this).text($(this).data('id'));   
   }); 
 })

$('.get-name').click(function() {    
   $('.person').each(function() {  
     $(this).text($(this).data('name'));   
   });
})

Answer №5

In my approach using Plain JavaScript:

Just like how Ilya utilized data- attributes, I also make use of them:

<div
  class="card"
  data-cardnumber="2"
  data-cardtype="Diamonds"
  data-cardowner="Alice"
></div>

<button data-type="cardnumber">Number</button>
<button data-type="cardowner">Owner</button>

Select all buttons and card elements:

var buttons = document.querySelectorAll('button');
var cards = document.querySelectorAll('.card');

Loop through the buttons and attach event listeners to them:

[].slice.call(buttons).forEach(function (button) {
  button.addEventListener('click', display.bind(this, button.dataset.type), false);
});

The function iterates over the cards in the collection and assigns the specified type passed into the function as argument[0] to their textContent.

function display() {
  for (var j = 0; j < cards.length; j++) {
    cards[j].textContent = cards[j].dataset[arguments[0]];
  }
}

DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize ajax requests to dynamically enable or disable input fields

Currently, I am developing an attendance management system for employees. The attachment below contains three input fields - one dropdown and two calendar fields. The dropdown includes the names of employees, the second field displays the current date and ...

How can I manually include a triangle in BufferGeometry using Three.js?

Recently, I've been exploring the quickest method to change a mesh's vertices using three.js. Through my experimentation, I discovered that modifying parts of mesh.geometry.attributes.position.array and then setting mesh.geometry.attributes.posit ...

What is the best way to transform a Ruby hash into a JavaScript object while maintaining unquoted values?

Is there a way to display a Ruby hash as a JS object without quotes for certain values in the hash, essentially as JS code? For instance, consider the following Ruby code: { foo: proc { 'someJavascriptFn()' } }.to_json How can I have the JS out ...

Why does the jQuery alert trigger only 40% of the time?

JavaScript -> if ($('.pagination').length) { $(window).scroll(function() { var url = $('.pagination .next_page').attr('href'); if ($(window).scrollTop() > $(document).height() - $(window).height() - 1 ...

Online support chat powered by jQuery AJAX

Does anyone know of a script that offers free online customer support using AJAX, JQUERY, and PHP? I'm looking for something that allows each person to have their own chat window... Thanks! ...

Creating hyperlinks in JSON response from a REST API with AngularJS - A guide!

I have a web application built with AngularJS, JS, JQ, and HTML5. This app can send various HTTP methods to the project's RESTful Web Service and receive responses in JSON format. The response is structured like this: When displayed in a <pre> ...

How can you stop queuing animations and timeouts in jQuery?

I'm facing a seemingly simple problem that I need help with. On my website, there's a hidden div.notification bar at the top. This bar can be displayed by adding either the success or warning class to it. There are two scenarios: either a messa ...

What could be causing the failure of this web component using shadow DOM when the HTML code includes multiple instances of the component?

Recently, a question was raised on this platform regarding the use of Selenium to access the shadow DOM. Curious about this topic, I delved into the MDN article Using shadow DOM and decided to replicate the code on my local machine. Surprisingly, it worked ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

Even though I am utilizing the `.then()` method, my asynchronous function continues to return a status of

Here is my code attempting to retrieve response data. const fetchRobots = () => { axios.get("https://jsonplaceholder.typicode.com/users").then((response) => { return response.data; }); }; let robotsData = fetchRobots(); console.log(robots ...

Bootstrap Table with Numerous Rows and Columns

I am striving to create a table layout similar to the one shown in the image using bootstrap 5. https://i.sstatic.net/lEnYX.png My attempt so far looks like this <table class="table table-bordered"> <thead> <tr> ...

Sending arrays' values in JavaScript

Here is a list of different groups to choose from: <select multiple="multiple" name="groups[]" id="groups[]" class="myclass"> <option value="1">Employees</option> <option value="2">Vendors</option> <option valu ...

Mongoose Wraps Every Item Inside a Collection

Hello everyone! I'm facing an issue with mongoose. It seems to be adding an array of arrays to the database instead of just an object array, and it's packaging each object into its own array. Can someone help me figure out what's going wrong ...

Automatically Importing in VSCode - A Guide to Enabling Full Path Imports for Material-UI

When utilizing the auto import function in VSCode to bring in Material-UI components, it defaults to a named import from the main file: import { Button } from "@material-ui/core" Nevertheless, I prefer the auto import to be a full path import li ...

Stopping an ajax timer when the results contain a specific key

I am currently working on a straightforward ajax function: <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script type="text/javascript"> function performAjaxRequest() { $.ajax({ ...

a way to globally access the value of useEffect beyond its scope

I encountered an issue where I initialized an array outside the useEffect and performed operations on it within the useEffect. Strangely, when I print the array inside the useEffect, I get the correct values. However, if I try to print the same array outsi ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Differentiating row colors in an HTML table using ng-repeat

I am trying to color the rows of a table alternatively with green and yellow using ng-repeat. I initially attempted to do this without ng-repeat and it worked as expected. .table-striped>tbody>tr:nth-of-type(odd) { background: yellow ! ...

The loading on the Express endpoint does not cease, despite configuring the response status (Encountering problems with Multer and Express)

Currently, I am in the process of developing a filter that evaluates a file's signature obtained through a file's buffer provided by Multer. While Multer supplies the MIME type, additional validation methods are required to confirm if the file ma ...

Cakephp routing issue preventing jQuery autocomplete from displaying values

I am currently working on implementing jQuery autocomplete to display data from my table in Cakephp. While I have successfully set up the autocomplete feature with tags, I am facing difficulty in fetching and displaying data from my table. The search funct ...