An illustration of tracking the `div` element with a class and data-id attributes using JavaScript (specifically jQuery)

There is a simple illustration

<button id="tri" style='display: block;'>click here</button>
        <div id="container" style='display: none;' >

Identified by id

$('#tri').on('click', function(){

            var e = document.getElementById('container');
            var b = document.getElementById('tri');
            if(e.style.display == 'none')
                $("#container").slideDown();
            b.style.display = 'none';
        })

We need to replicate this for another button that identifies only by class and data-id

<div class="section_view" data-id="13" style='display: none; ></div>

My attempt did not yield the expected result

<button class="modifysection" data-id="14">modify</button>

<div class="section_edit" style="display: none;" data-id="14"></div>

<script>
    $('body').on('click', '.modifysection', function() {
        var $this = $(this),
            id = $this.attr('data-id'); 
        var section = $('.section_view[data-id=id]');
        if(section.style.display == 'none')
            section.style.display = 'block';
    })
</script>

What mistake am I making?

Answer №1

Make sure to handle the dynamic data in the variable id properly when using it as part of a selector.

When referencing a jQuery element with b, consider using .css() instead of directly manipulating the style property.

Take a look at this revised approach:

$('body').on('click', '.editblock', function() {
  var $this = $(this),
  id = $this.attr('data-id'); 
  var b = $('.block_view[data-id='+id+']');
  if(b.css('display') == 'none')
    b.css('display', 'block');
  else b.css('display', 'none');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button class="editblock" data-id="51">edit</button>

<div class="block_view" data-id="51" style='display: none;' >block_view</div>

Answer №2

Make sure to include the id variable within the selector, rather than inserting the literal string "id". Additionally, keep in mind that jQuery returns a jQuery object, not an element, so document.querySelector may be a better option.

var x = document.querySelector('.block[data-id="'+id+'"]');

Answer №3

To access the data-id, you can use $(this).data('id'); and get the style by using $(this).css("display"). By targeting all div elements with the specific data-id, you can then show or hide them accordingly.

$(".editblock").click(function() { 
  var id=$(this).data('id'); 
   console.log(id)
   var styles = $(this).css("display");
   console.log(styles)
     $("div").each(function(){
        if($(this).attr('id') == id  && $(this).css("display")=="none") {
            $(this).css('display','block');
        }
    });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button  class="editblock" data-id="51">edit</button>

 <div class="block_edit" >
 
 <div id="51" style="display:none">div1</div>
 <div id="52" style="display:none">div2</div>
 <div id="53" style="display:none">div3</div>
 
 </div>

Answer №4

<!DOCTYPE html>
<html>
<head>
    <title></title>

</head>
<body>
    <button class="editblock" data-id="51">click to edit</button>
    <div class="block_edit" style="display: none;" data-id="51"></div>
    <div class="block_view" data-id="51" style='display: none;'>Demo Content</div>

</body>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script type="text/javascript"  src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<script>
    $('.editblock').click(function(){

          var id = $(this).attr('data-id'); 
          var b = $('.block_view[data-id='+id+']');
                if($(b).css('display')=='none'){
                    $(b).css('display','block')
                }
          });

</script>
</html>

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

Ways to identify when a user presses the back or forward arrow on a browser using JavaScript or jQuery for a non-single page application (

There are only 2 routes available: / and /about When on the following URLs: localhost:8080 -> it displays the home page localhost:8080/about -> it shows the about page If a user opens the home page, clicks on the about button, and goes to the abou ...

Print out the value of the element in the array using the console

Hey there! I have this array that I retrieved from MongoDB and I'm trying to figure out how to console log the value of item. Any tips or suggestions would be greatly appreciated! { "_id" : "61462a7bf3c0be993bcfdc3e", "item&qu ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

Utilizing CSS flexbox to occupy the remaining vertical space

I'm facing a scenario where I have three elements: div with content 1, div with content 2, and an image that spans 100% width (with variable height). My goal is to align div 1 at the top, the image at the bottom, and fill the remaining space with cont ...

Managing properties of classes within callbacks using TypeScript

I am currently working on the following task: class User { name: string; userService: UserService; //service responsible for fetching data from server successCallback(response: any) { this.name = string; } setUser() { ...

Tips for introducing a pause between asynchronous line reads when utilizing the readline module in Node.js

In Node.js, I am able to stream a file line-by-line by using the following code snippet: var rd = readline.createInterface({ input: fs.createReadStream('/path/to/file'), output: process.stdout, terminal: false }); rd.on('line', ...

Tips for effectively managing errors (whether they are in the form of strings or objects) in express.js with the

While I have experience working with express.js applications, I am still trying to find the most effective way to handle errors. Since io.js has been a reality for a few months now, I have started using native Promises to manage asynchronous operations. T ...

The CSS background image is not displaying, but when I place it as a regular image, it does show up

My CSS code at the root of the file is set up to check the issue I'm about to explain: .why-choose-us-image { width: 100%; height: 100%; background-position: center center; background-size: cover; background-repeat: no-repeat; } . ...

When registering the onHardwareBackButton event in Ionic, the back button continues to successfully navigate to the previous page

I recently started working with Ionic and encountered an issue with the onHardwareBackButton event. The event is functioning properly and directing me to the register function, but even after going to the register function, it still navigates back to the p ...

The data type 'string' cannot be assigned to the type 'Message' in NEXT.JS when using TypeScript

Currently, I am undertaking the task of replicating Messenger using Next.Js for practice. Throughout this process, I have integrated type definitions and incorporated "Upstash, Serverless access to the Redis database" as part of my project. I meticulously ...

What is the process for transforming an asynchronous method into a synchronous version?

I am currently working on creating a functionality similar to the core fs module's methods, where there is an Async method by default and a Sync method if requested like fs.readDir() and fs.readDirSync(). In my case, I have a method named fetchUrls w ...

Set up a listener to detect changes in fullscreen mode for the specified host

How can I determine if the fullscreen mode is active using the HTML5 fullscreen API with Chrome and Angular 4.x? I have developed an Angular component and included the following @HostListener: @HostListener('document:webkitfullscreenchange', ...

Adding a variety of data types to a MongoDB collection through Node.js

I'm currently using the Sails web framework along with Node.js and MongoDB to develop my own website. I am encountering some challenges while attempting to add a new user and input values (of different types: Number, Array, Object) to my 'users&a ...

In the realm of jQuery, erasing dynamically generated elements across multiple elements sharing the same index is a task

Currently, I am enhancing the select box dropdown and list of new fonts by adding custom font names. In addition to this, I also want to incorporate a feature for deleting fonts. For instance, when I delete font A from the list (which is currently functio ...

Best way to pass a variable from an html form to a php function using ajax

I am currently developing a voting system for multiple uploads where each uploaded image is within a foreach statement. Each image has a form attached to it with three buttons to vote up, down, or not at all. These buttons are associated with an INT value ...

Is there a way to verify the format of a date string that includes a timezone?

Is there a way to validate the format of this date: April 14, 2022 14:00 UTC, ensuring it follows the pattern MMMM DD, YYYY HH:mm <timezone>? I attempted using moment for validation, but it lacks support for timezone formatting. moment(date, 'M ...

The loading of jQuery's 'Galleria' stops unpredictably

The issue at hand revolves around a jQuery gallery known as 'Galleria'. It's visually appealing and since my client is a Photographer, I decided to showcase all of his images in a Galleria gallery. You can view the website, currently in its ...

Locate the dynamically created HTML element and set its value

I have a situation where I am dynamically generating HTML input text controls using a string builder and placing them inside a div from Code Behind. After generating these inputs, I also need to assign values to them and update the database if the user ch ...

Navigating a dropdown menu in an Asp.net application: choosing an option

I am currently working on an ASP.net project that incorporates Bootstrap controls. The issue I am facing involves a Bootstrap dropdown menu that dynamically populates its list items from a database. The problem arises when I click on the menu and select a ...

Issue with the footer occurring prior to displaying the content

After trying numerous solutions like flexbox and positioning, I still can't figure out how to place my footer component at the bottom before the container component is rendered. With an asynchronous data spinner loading above it, the layout looks quit ...