How to get highlighted words and wrap it in new element with data-attribute?


Tags: javascript,jquery,html,css,html5-data

Problem :

JSFIDDLE

HTML:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>

CSS:

.highlight {
  color: red;
}

JS:

$(function(){

  $('p').click(function(){
    // get highlighted words

    // get user input
    var user_input = window.prompt();

    // put highlighted words in <span class="highlight"></span> element
    // and add data-id to the span element
    // expected output:
    // <p>... <span class="highlight" data-id="user input here">highlighted words here</span> ...</p>
  });

});

I have a block of text in p tag and I want it to be like this:

  1. User select some word(s) inside the block
  2. User enter something inside the prompt box
  3. Put the highlighted word(s) inside span tag with data-attribute (I'd called it data-id) and this data-attribute value is coming from the prompt (step 2 above)

How do I achieve this?

Please help me.



Solution :

With the help of fiddle given in the comment you can achieve it as below:

function selectHTML() {
  try {
    if (window.ActiveXObject) {
      var c = document.selection.createRange();
      return c.htmlText;
    }

    var nNd = document.createElement("span");
    var w = getSelection().getRangeAt(0);
    w.surroundContents(nNd);
    return nNd.innerHTML;
  } catch (e) {
    if (window.ActiveXObject) {
      return document.selection.createRange();
    } else {
      return getSelection();
    }
  }
}

$(function() {
  $('p').click(function() {
    var selected = selectHTML();
    var user_input = window.prompt();
    $('span').addClass('highlight').attr('data-id', user_input);
  });
});
.highlight {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan
  augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet
  gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>


    CSS Howto..

    jQuery, given a Variable with DIV with items, how to scroll an Item to the Left

    How can I change the number of columns in the product list?

    CSS how to use pseudo-class :not with :nth-child

    can't find out how to create a css selector for yahoo stocks page

    How to specify styles for h:panelgrid in jsf

    How to vertically align absolutely positioned images on top of one another?

    How to link a main.css to all Django templates? [closed]

    How to link to a CSS if a certain condition happens?

    How to set the container height automatically maintaining the ratio

    How to hide text without ID?

    How to structure selectors in css when using specificity?

    How to customize HTML/CSS tooltips?

    How to select only some children in CSS?

    How do I know when is the right moment to stop using a specific css vendor-prefix?

    How to make in CSS an overlay over an image?

    CSS, how to create a label width of the longest containing text?

    How to set a menu hover delay

    javafx ImageView how to use css hover

    How do i hook media queries to screen resolution?

    Show submenu with CSS without using an unordered list

    How to Keep element absolute at their location bootstrap 3

    How to style a particular paragraph element in css without effecting the other paragraphs in the same class?

    CSS, Javascipt, HTML, how can i align a text inside a div to middle beside an image? and animate the text

    How to normalize a button and an anchor with CSS?

    How to create a static footer in CSS?

    How to create CSS heart? / Why is this CSS creating a heart shape?

    How to create a firefox addon which injects CSS into a page? [closed]

    How to use opacity when not use rgba color in css?

    How to strikethrough empty div

    How to add CSS to a specific div class - WordPress