简体   繁体   中英

trying to print the value in a html tag with a class attribute using javascript

I am trying to print the content in a html tag using its css value if the content in the html is not empty. This is snippet from the javascript code block

<script>

    jQuery(document).ready(function(){

    function myFunction() {
    var x = document.getElementsByClassName("simpleproduct");
    if(x != null){
    var y = x[0].innerHTML;
    alert(y);

    }
}

});
        </script>

this is the button that calls the javascript function

<button onclick="myFunction()">ClickToSee</button>

this is a sample html tag with css value

<h5 class="simpleproduct">199.99</h5>

please how do I get the value in a html tag using the class attribute.

 jQuery(document).ready(function() {}); function myFunction() { var x = document.getElementsByClassName("simpleproduct"); if (x != null) { var y = x[0].innerHTML; alert(y); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="myFunction()">ClickToSee</button> <h5 class="simpleproduct">199.99</h5> 

put the function outside of the jquery.ready

As you are using jQuery its as simple as this

 $(document).ready(function(){ $('#myButton').on('click', myFunction); function myFunction() { var text = $(".simpleproduct").text(); alert(text); } }); 
 <button id="myButton">ClickToSee</button> <h5 class="simpleproduct">199.99</h5> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Note: simpleproduct selector could be more refined to return only one element based on complete template structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM