Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix id handling #112

Merged
merged 2 commits into from Apr 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/nodes/html.ts
Expand Up @@ -131,6 +131,7 @@ export default class HTMLElement extends Node {
super(parentNode);
this.rawTagName = tagName;
this.rawAttrs = rawAttrs || '';
this.id = keyAttrs.id || '';
this.childNodes = [];
this.classList = new DOMTokenList(
keyAttrs.class ? keyAttrs.class.split(/\s+/) : [],
Expand All @@ -139,7 +140,6 @@ export default class HTMLElement extends Node {
)
);
if (keyAttrs.id) {
this.id = keyAttrs.id;
if (!rawAttrs) {
this.rawAttrs = `id="${keyAttrs.id}"`;
}
Expand Down Expand Up @@ -609,6 +609,10 @@ export default class HTMLElement extends Node {
}
return `${name}=${val}`;
}).join(' ');
// Update this.id
if (key === 'id') {
this.id = '';
}
}

public hasAttribute(key: string) {
Expand Down Expand Up @@ -653,6 +657,10 @@ export default class HTMLElement extends Node {
}
return `${name}=${val}`;
}).join(' ');
// Update this.id
if (key === 'id') {
this.id = value;
}
}

/**
Expand Down
39 changes: 39 additions & 0 deletions test/112.js
@@ -0,0 +1,39 @@
const { parse, HTMLElement } = require('../dist');

// https://github.com/taoqf/node-html-parser/pull/112
describe('pull/112', function () {
it('this.id is set to an empty string', async function () {
const el = new HTMLElement('div', {}, '', null);
el.id.should.eql('')
should.equal(el.getAttribute('id'), undefined);
el.toString().should.eql('<div></div>');
});
it('this.id is set to the value of keyAttrs', async function () {
const el = new HTMLElement('div', { id: 'id' }, 'id="id"', null);
el.id.should.eql('id')
el.getAttribute('id').should.eql('id')
el.toString().should.eql('<div id="id"></div>');
});
it('#removeAttribute()', async function () {
const html = '<div id="id"></div>';
const root = parse(html);
const el = root.firstChild;
el.id.should.eql('id')
el.getAttribute('id').should.eql('id')
el.removeAttribute('id')
el.id.should.eql('')
should.equal(el.getAttribute('id'), undefined);
el.toString().should.eql('<div></div>');
});
it('#setAttribute()', async function () {
const html = '<div></div>';
const root = parse(html);
const el = root.firstChild;
el.id.should.eql('')
should.equal(el.getAttribute('id'), undefined);
el.setAttribute('id', 'id')
el.id.should.eql('id')
el.getAttribute('id').should.eql('id')
el.toString().should.eql('<div id="id"></div>');
});
});