1

I'm trying to add 'checked' attribute to HTML string, which contains multiple HTML tags.

let someBtn = `<div class='btn'><input type='checkbox' id='${item.Id}' 
                            value='Some value' class='active-btn'> <label class='btn' 
                            for='${item.id}'></label></div>`;```

Doing it this way:

var something = $($.parseHTML(someBtn)).find('input[type=checkbox]').attr('checked', 1).prop('outerHTML');

returns only the tag, not the whole updated HTML string. Also that input tag gets checked="checked" attribute instead of just checked. Why is that? I cannot use attr('checked', true) - there's no method with this kind of parameters.

Could somebody please help me out with this problem - to return the whole HTML string with proper checked attribute?

1
  • 1
    Also that input tag gets checked="checked" attribute instead of just checked. Why is that? — Because the browser normalises it and uses the full name=value and not the shorthand. Commented Apr 23, 2019 at 12:36

1 Answer 1

2

Useless to do $($.parseHTML('html_string')), you can directly use $('html_string').

You also need to seperate the fact to update your checkbox attributes and the fact to get the HTML.

const someBtn = `<div class='btn'><input type='checkbox' id='myId' 
                            value='Some value' class='active-btn'> <label class='btn' 
                            for='myId'></label></div>`;
                           
let html = $(someBtn);

html.find('input').attr('checked', 1);

html = html.prop('outerHTML'); // or html[0].outerHTML

console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

In my case prop() returns only the element selected by find().
That's why you need to divide some parts of your logic, as I did in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.