Access data in JavaScript regardless of the specific element name

In an attempt to target a modal without an id or class, I am faced with a challenge. This is because the team page in our CMS assigns a unique

data-modal="NAME-I-WILL-NOT-KNOW"
for each team member added.

The "NAME-I-WILL-NOT-KNOW" part of the code is controlled by the CMS.

For example: If a client adds a new team member named "Bob Smith", the resulting HTML code will be:

Button

<div class="button-wrap">
  <a rel="modal:open" class="button is-danger is-rounded modal-button" data-modal-target="bobsmith" aria-haspopup="true">
    <span>View Profile</span>
  </a>
</div>

Modal

<div id="modalopen" class="modal" data-modal="bobsmith">
</div>

I have attempted various methods using document.querySelector, but none seem quite right. The following seems like a step in the right direction.

var modal = document.querySelector("[data-modal=" + target + "]");

Unfortunately, this method does not work as expected.

I've excluded the CMS elements in this demo for clarity purposes.

I thought that sharing the CSS and HTML structure would help explain my issue better.

Answer №2

To create a modal, you can utilize the btn.onclick event like this:

btn.onclick = function openModal(event) {

    var target = this.dataset.modalTarget;
  
    // Get the modal
    var modal = document.querySelector("[data-modal=" + target + "]");
    modal.style.display = "block";
}

Make sure to define the modal variable first and include some checks in other listeners using modal. The following snippet provides a corrected version:

var modal = undefined;

// Get the button that opens the modal
var btn = document.getElementById("modal_open");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal-close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function openModal(event) {

    var target = this.dataset.modalTarget;
    
    // Get the modal
    modal = document.querySelector("[data-modal=" + target + "]");
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    if (modal === undefined) return;

    modal.style.display = "none";
}

// Close the modal when clicking outside of it
window.onclick = function(event) {
    if (modal === undefined) return;

    if (event.target == modal) {
        modal.style.display = "none";
    }
}
.team {
  /* CSS Styles for the team section */
}

/* Additional CSS styles as per requirement */

If your CMS handles the target variable differently, there might be a more suitable solution for your scenario. You can also extend the above solution to handle multiple buttons simultaneously by using

document.querySelectorAll('[data-modal-target]')
to select all buttons at once and iterate over them.

Answer №3

You need to remember to include the quotes correctly. The correct format is "[data-modal='bobsmith']". Give this a try:

var modal = document.querySelector("[data-modal='" + target + "']");

Answer №4

I appreciate all the assistance from everyone. Your responses have guided me towards a new inquiry that ultimately resulted in finding a comprehensive solution.

For further details, refer to Denis Mysenko's response in this discussion

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

Guide to dynamically adding a class in VueJS based on a certain condition

I'm in the process of transitioning a project to Vue, and I'm curious about how I can dynamically assign classes to specific elements based on database values rendered with Vue. Previously, I had this code set up without Vue: $(document).ready(f ...

JavaScript function is returning 'undefined' instead of an integer

My JavaScript/jQuery function is not functioning correctly and instead of returning an integer, it returns undefined. function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active&apo ...

Verify that the value being returned is in the form of a promise

Provided an angular controller containing the following function: this.checkResponse = function (response) { if (response.success === true) { return $q.resolve(response); } else { return $q.reject(response); } }; I am looking to test with J ...

Clicking on an object will trigger the threejs to traverse through

I need to implement a wireframe for an object when a button is clicked. I am using the traverse function to achieve this, and it works perfectly fine in the OBJMTLLoader. However, when I try to use it in a separate function as shown below and then click th ...

Adding optional properties to TypeScript interfaces

As discussed in this post, the optional ? operator is commonly used to indicate that a function parameter can be omitted. But what is the significance of the ? operator when it appears on interface parameters? For instance, consider the following TypeScrip ...

Question about Looping Concept

var answer = ""; var correct = "4"; var question = "What is 2 * 2?"; for(i = 2; i < 5; i++) { answer = prompt(question, "0"); if (answer == correct) { alert("Your answer is correct!"); break; } } Before the break command is ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Issue with retrieving the ID of a dynamically created element with jQuery

Whenever I try to execute my function to display the id for a click event of a tag that has items appended dynamically, the alert does not show the id. Instead, it displays 'undefined'. Can anyone help me figure out where I am going wrong? Here ...

Is there a way to extract the unicode/hex representation of a symbol from HTML using JavaScript or jQuery?

Imagine you have an element like this... <math xmlns="http://www.w3.org/1998/Math/MathML"> <mo class="symbol">α</mo> </math> Is there a method to retrieve the Unicode/hex value of alpha α, which is &#x03B1, using JavaScrip ...

When the chart is zoomed in, Highcharts displays points outside the chart area when hovering over the line

I recently began working with highcharts and for my current project, I need a prototype chart that allows zooming in and out. Specifically, I want to display the y-axis value in the tooltip only when the user hovers directly over the points. However, in hi ...

Utilizing base classes in callbacks with ES6 in NodeJS

Consider this scenario where I have a class as shown below: class X extends Y { constructor() { super(); } method() { asyncMethod( function( err ) { super.method( err ); } ); } } The issue here is that super actually ...

Adjust the sound levels with a sleek jQuery UI volume slider

Currently, I am working on developing a customized volume slider for FlowPlayer that is built upon the standard jQuery UI Slider. I am seeking assistance in establishing a connection between this slider and the HTML5 video volume controls. Below is the co ...

Troubleshooting the compatibility issues between Angular and D3.js V4 Zoom functionality

I am currently using D3 v4 and Datamaps within my angular project, attempting to implement zoom functionality. However, I am encountering an issue that has left me puzzled. Within my code, I have a function responsible for creating the map: public create ...

Unable to resolve the issue within Angular UI modal

Currently, I am facing an issue with displaying a modal using Angular Bootstrap UI. The modal is supposed to resolve items in the controller, but I am struggling to access those resolved items in the modal controller. $scope.showItemsInBill = function(bill ...

What is the process for creating a list using layers that are published in Geoserver?

I am currently working on developing a webmapping application. One of the tasks I need to accomplish is parsing the WMS request in order to retrieve the title of each layer within the layers section: var xhr = new XMLHttpRequest(); xhr.open(' ...

What is the best way to extract information from a JavaScript page when the content is identified by a reference?

If you're looking for the website, you can visit . It's primarily in Chinese, but that may not be relevant to the topic at hand. Currently, I am able to extract all the content from this page and now I'm interested in moving on to the next ...

Tips for making objects rotate vertically on their axis and orbit around another object in three.js

Thank you in advance for all the support as I've been asking a lot of questions about my project. My project involves creating a simulation where a planet earth and moon rotate around a sun. (They're not exactly rotating around the sun, but more ...

Listeners for JavaScript actions

My typical approach to implementing a select box is as follows: <select size="1" name="example_length" onchange="callSomeMethod"> <option value="10" selected="selected"></option> <option value="25">25</option> < ...

Retrieving constant values from a JSON object

Here is an example of a JSON object: [ [ "A", "1" ], [ "B", "2" ], [ "C", "3" ], [ "D", "4" ], [ "E", "5" ], [ "F", "6" ] ] Is there a way to retrieve all the key/value pairs except for A and D ...