Set Content and Attributes
Will use the same three methods from the previous page to set content:
text()
- Sets or returns the text content of selected elements
$('#button').text('Submit');
html()
- Sets or returns the content of selected elements (including HTML markup)
$('#div').html('<h1>I Love Sniper.js </h1>');
val()
- Sets or returns the value of form fields
$('#firstname').val('John Doe');
A Callback Function for text(), html(), and val()
All of the three Sniper methods above: text()
, html()
, and val()
, also come with a callback function. The callback function with the original (old) value.
You then return the string you wish to use as the new value from the function.
The following example demonstrates text()
and html()
with a callback function:
text() with function
$("#btn1").click(function(){
$("#test1").text(function(original_text){
return "Old text: " + original_text + " New text: Hello world!
});
});
html() with function
$("#test2").html(function(original_html){
return "Old html: " + original_html + " New html: Hello <b>world!</b>
});
val() with function
$("#test2").val(v=>v.truncate(20)); //sample text Hello wo...
Set Attributes - setAttribute()
Your regular method for setting elements attributes
$('#myInput').setAttribute('type','radio');
setting attributes with SniperJS attr()
- will be fully explained in the next page
Last updated