any error with onclick with data-id here?

Yosra MH Source

is there any mistake with my code? I want to show/hide the section everytime I click the button using the data-id as I have different sections:

function myFunction() {
    var foo = $("section").data("id");
    if (foo.style.display === "none") {
        foo.style.display = "block";
    } else {
        foo.style.display = "none";
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="myFunction()">Try it</button>
    
<section data-id="mySection">
    This is my Section element.
</section>

javascript

Answers

answered 5 days ago Mamun #1

You can try with Document.querySelector()

document.querySelector('section[data-id=mySection]')

function myFunction() {
  var foo = document.querySelector('section[data-id=mySection]');
  if (foo.style.display === "none") {
    foo.style.display = "block";
  } else {
    foo.style.display = "none";
  }
}
<button onclick="myFunction()">Try it</button>

<section data-id="mySection">
  This is my section element.
</section>
<section>
  This is another section.
</section>

answered 5 days ago Martin D. #2

You could use the id attribute instead of data-id.

function myFunction() {
    var foo = $("#mySection"); //use the id selector
    // but if you need to use the data-id attribute you can do this
    // var foo = $("section[data-id=mySection]");

    if (foo.css("display") === "none") { //then you can use jquery's css() function
        foo.css("display", "block");
    } else {
        foo.css("display", "none");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="myFunction()">Try it</button>
    
<section id="mySection">
    This is my Section element.
</section>

answered 5 days ago Sushanth -- #3

$('section[data-id="mySection"]') is the selector if you are looking to target the element.

$('button').on('click', myFunction);

function myFunction() {
    var $elem = $('section[data-id="mySection"]');
    
    $elem.toggle($elem.is(':hidden'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Try it</button>

<section data-id="mySection">
    This is my Section element.
</section>

comments powered by Disqus