Mario Uher
Mario Uher

Reputation: 12397

Find similar HTML parts

I have following (simplified) HTML code and want to split it into similar parts:

<input id="checkbox1"><label><br>
<input id="checkbox2"><label><br>
<input id="checkbox3"><label><br>

The result for this should be <input><label><br>. But the problem is, I need a bulletproof solution, which would for example return <div><p><input></p><p><label></p></div> from the following HTML:

<div><p><input id="checkbox1"></p><p><label></p></div>
<div><p><input id="checkbox2"></p><p><label></p></div>
<div><p><input id="checkbox3"></p><p><label></p></div>

Any idea how to find such a pseudo parent element in JavaScript/jQuery?


Like Rory McCrossan figured out, this is indeed used for a templates system. The user defines one row in this template, like <input id="checkbox1"><label><br> which is then displayed x times on the screen. I need this template in my JS code, but there is unfortunately no direct access to the user template, so my idea was to figure out which HTML parts look similar and the splitting them to get the template back.

Upvotes: 1

Views: 336

Answers (1)

user1726343
user1726343

Reputation:

As a partial solution, you could consider identifying the closest common ancestor for an input label pair, and using this as the repeating element:

var collection = $('');
$('input').each(function() {
    collection = collection
        .add($(this)
             .parents(':has(label)')
             .filter(function() {
                 return $(this).siblings().length == $(this).siblings(this.tagName).length;
             }));
});
console.log(collection);

This presupposes each label input pair has a common parent element, and so doesn't work for your first case.

Upvotes: 1

Related Questions