querySelectorAll

querySelectorAll

by Imri Paloja

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>
<div class="container">

<button onclick="Bold();">
B
</button>

  <div contenteditable="true">
    <header>
      <h1>Rich Text Editing Development</h1>
      <p>I'm <strong><em>really</em> annoyed</strong> with trying to figure out this answer.</p>
    </header>
  </div>

</div>

CSS

html,
body {
  color: #454545;
}

.container {
  margin-top: 5%;
}

JavaScript

function Bold() {

  // https://stackoverflow.com/a/49881456/1148529
  console.clear();

  const selection = window.getSelection();
  if (!selection.rangeCount) return;

  const range = selection.getRangeAt(0);

  //console.log('Selected elements:');
  //range.cloneContents().querySelectorAll('*').forEach(e => console.log(e..tagName));

  Tags = range.cloneContents().querySelectorAll('*');

  Tags.forEach(function(tag) {
  
    if (tag.tagName == 'STRONG') {

      console.log('Found the strong tag');

    } else {
      console.log('DID NOT FIND THE STRONG TAG');
    }


  });


  //console.log('Selected text/elements parent:');
  // console.log(range.commonAncestorContainer.parentNode);

}