Reputation: 17467
I have a bit of code that updates the html of a div. This div is only on one page and the js is site wide.
$('#mydiv').html('<p>hello</p>');
Should I check the div exists or just leave it to try and fail to find the div?
Upvotes: 0
Views: 1151
Reputation: 854
I think the best answer its "depend". Whitout a div with id #mydiv you operation fail, so html won't be set.
If you are interested on show something to user, operation fail and no result will be reach.
The simplier way is to ensure the presence of elements you need to manipulate, by putting them directly into html.
Another way is to ensure element presence by jQuery contol, i.e.:
if($("#mydiv").length==0)
$("body").append("#mydiv");
$('#mydiv').html('<p>hello</p>');
Of course, you have to know where insert it, and an absolute parent for that elemente. by theway, as i said,if possible, it is easier to put div directly to html.
Upvotes: 1
Reputation: 182
the best practice is to have a validation over that kind controls. so my suggestion is to use code
HTML
<div id="mydiv"></div>
<input type="button" id="chk" value="button"/>
JQUERY
$('#chk').click(function() {
var len=$('#mydiv').length;
if(len>0)
{
$('#mydiv').html('<p>hello</p>');
}
});
Upvotes: -1
Reputation: 26143
There are actually 2 things taking place there. Firstly is this...
$('#mydiv')
That finds all elements that match the selector and returns them as an array of jQuery objects. Then you have this...
.html('<p>hello</p>');
That will only run against jQuery objects in the preceding array.
In a nutshell, that line includes checking that the element exists, so you don't have to do it.
Note that this is only the case because they are jQuery functions and jQuery is just nice to developers. If you were to do something like this then it could fail...
$('#mydiv').text().replace("a", "b");
That's because text()
returns a string and the replace
would fail if there was no string, as that would be undefined
. As soon as you break out of the jQuery functions back into vanilla Javascript then you (often) have to start thinking about whether things exist or not.
Upvotes: 2