Skip to content

Commit

Permalink
feat(attributes): Add textContent and innerText props (#2214)
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 authored Nov 19, 2021
1 parent f0169e1 commit 3af9e67
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/__fixtures__/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,14 @@ export const noscript = [
'</body>',
].join('');

export const script = [
'<div>',
'<a>A</a>',
'<script>',
' var foo = "bar";',
'</script>',
'<b>B</b>',
'</div>',
].join('');

export const mixedText = '<a>1</a>TEXT<b>2</b>';
17 changes: 17 additions & 0 deletions src/api/attributes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import cheerio from '..';
import type { Cheerio } from '../cheerio';
import type { Element } from 'domhandler';
import {
script,
fruits,
vegetables,
food,
Expand Down Expand Up @@ -296,6 +297,22 @@ describe('$(...)', () => {
expect($a.prop('innerHTML')).toBe('<a></a>');
});

it('("textContent") : should render properly', () => {
expect(selectMenu.children().prop('textContent')).toBe(
'Option not selected'
);

expect($(script).prop('textContent')).toBe('A var foo = "bar";B');
});

it('("innerText") : should render properly', () => {
expect(selectMenu.children().prop('innerText')).toBe(
'Option not selected'
);

expect($(script).prop('innerText')).toBe('AB');
});

it('(inherited properties) : prop should support inherited properties', () => {
expect(selectMenu.prop('childNodes')).toBe(selectMenu[0].childNodes);
});
Expand Down
9 changes: 8 additions & 1 deletion src/api/attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { text } from '../static';
import { isTag, domEach, camelCase, cssCase } from '../utils';
import type { Node, Element } from 'domhandler';
import type { Cheerio } from '../cheerio';
import { innerText, textContent } from 'domutils';
const hasOwn = Object.prototype.hasOwnProperty;
const rspace = /\s+/;
const dataAttrPrefix = 'data-';
Expand Down Expand Up @@ -300,7 +301,7 @@ export function prop<T extends Node>(
): T extends Element ? string : undefined;
export function prop<T extends Node>(
this: Cheerio<T>,
name: 'innerHTML' | 'outerHTML'
name: 'innerHTML' | 'outerHTML' | 'innerText' | 'textContent'
): string | null;
export function prop<T extends Node>(
this: Cheerio<T>,
Expand Down Expand Up @@ -361,6 +362,12 @@ export function prop<T extends Node>(
return isTag(el) ? el.name.toUpperCase() : undefined;
}

case 'innerText':
return innerText(this[0]);

case 'textContent':
return textContent(this[0]);

case 'outerHTML':
return this.clone().wrap('<container />').parent().html();

Expand Down

0 comments on commit 3af9e67

Please sign in to comment.