0

I'm using JavaScript to try and create a regular expression that will find (in an html file) all divs that don't have an onclick attribute.

Example:

This div should be ignored..

<div class="foo"
     id="bar"
     onclick="someFunction()>some text</div>

This div should be matched (because it doesn't contain an onclick attribute)..

<div class="foo"
     id="bar">some text</div>

I tried this but it doesn't work..

var pattern = /div[\s\w\n\=\(\)"]*(?!onclick)div[\s\w\n\=\(\)"]*">/

I'm guessing that the first part of my regular expression (before the negative look-ahead) is actually matching the negative look-ahead.

Can someone help? Thanks in advance for any suggestions.

Mikev
  • 2,012
  • 1
  • 15
  • 27
Gerald LeRoy
  • 1,227
  • 2
  • 11
  • 17
  • 1
    Possible duplicate of [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). You can't match HTML with regex. – Jack Bashford Mar 12 '19 at 09:17
  • 1
    Could you not just use querySelector with an appropriate selector? You should always prefer direct node access instead of string based searches. – James Coyle Mar 12 '19 at 09:18

1 Answers1

2

Why not use querySelectorAll instead? div:not([onclick]) will select <div>s which do not have an onclick attribute.

document.querySelectorAll('div:not([onclick])')
  .forEach((div) => {
    console.log(div);
  });
<div class="foo" id="bar" onclick="someFunction()">some text</div>
<div class="foo">some text 2</div>

If you only have a string and so can't use querySelectorAll on it directly, you can transform it into a document safely with DOMParser:

const htmlText = `<div class="foo" id="bar" onclick="someFunction()">some text</div>
<div class="foo">some text 2</div>`;
const doc = new DOMParser().parseFromString(htmlText, 'text/html');

doc.querySelectorAll('div:not([onclick])')
  .forEach((div) => {
    console.log(div);
  });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320