0

I would like to be able to assign an html element to a variable and then to work with it just like I'm working with the actual DOM element.

In this example, I want it so when showAlert() function gets called, it'll take the ID that is being passed, show the div, since it's default is hidden and set a text value inside the DIV.

What is the best way to do this?

HTML:

<div class="alert" id="myCustomAlert12345" style="display:none" >
</div>

Javascript:

function showAlert(alertDivID, alertMessage, alerttype){        
        if(alertDivID&& alertMessage){
            currentDiv = $('#'+alertDivID);             
            currentDiv.show();
            currentDiv.html(alertMessage);
        }
}

showAlert("myCustomAlert12345","some error message goes here","error");
Andre
  • 603
  • 7
  • 19

2 Answers2

0

You can pass jQuery objects into a function.

var showAlert = function ($el, mes){                   
    $el.show();
    $el.append('<p>'+ mes +'</p>');
};

showAlert($('.item'), 'My Message');
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

You could do something like this the below. This will use the id you pass and show the div with the appropriate message. You just need to make sure that you wait for the DOM to completely load before checking for the elements.

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.7.1.js"></script>
</head>
<body>
    <div class="alert" id="custAlert" style="display: none"></div>
    <input type="button" class="showError" value="click me to show error" />

    <script type="text/javascript">
        function showAlert(divID, msg) {
            $('#' + divID).html(msg);
            $('#' + divID).show();
        }

        $(function() {
            $('.showError').click(function() {
                showAlert('custAlert', 'this is an error');
            });
        });
    </script>

</body>

</html>
Sam
  • 345
  • 5
  • 17