I have a string representing a checkbox such as follows:
var checkbox = "<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1"/></label></div>";
I want to make the checkbox checked (add the attribute checked="checked") such that the string becomes:
<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1" checked="checked"/></label></div>;
I have tried the following:
$(checkbox).find('input').attr('checked', true).end().html();
This return the following:
<label for="cb_1"><input type="checkbox" id="cb_1" checked="checked"/></label>
My question is why is the first div not returned and how can I return the whole thing like:
<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1" checked="checked"/></label></div>;
html()
in jquery uses innerHTML
property. In this case, outerHTML
need to be used, So
Try using prop('outerHTML')
var checkbox = '<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1"/></label></div>'; console.log($(checkbox).find('input').attr('checked', true).end().prop('outerHTML'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Reference
https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
尝试这个
$($(checkbox).find('input').attr('checked', true).end().parentNode).html();
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.