Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full word containing a specific element

Having the reference to a specific DOM element (e.g. <mark>), how can we get the full word containing that element?

For example :

H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!

I expect to get the following output :

  • First <mark>: Hello
  • Second: World
  • Third: Hello
  • Fourth: Pluto

var $marks = $("mark");

var tests = [
  "Hello",
  "World",
  "Hello",
  "Pluto",
];

function getFullWord($elm) {
  // TODO: How can I do this?
  // 		   This is obviously wrong.
  return $elm.html();
}

var $marks = $("mark");
tests.forEach(function(c, i) {
  var word = getFullWord($marks.eq(i));
  if (word !== c) {
    alert("Wrong result for index " + i + ". Expected: '" + c + "' but got '" + word + "'");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!
like image 595
Ionică Bizău Avatar asked Jun 05 '16 08:06

Ionică Bizău


1 Answers

If you need fast and compact code (one-liner), try this:

var $marks = $('mark');

$marks.each(function() {
    var wholeWord = (this.previousSibling.nodeValue.split(' ').pop() + 
                     this.textContent + 
                     this.nextSibling.nodeValue.split(' ')[0]
                     ).replace(/[^\w\s]/gi, '');
});

JSFiddle (with logging into console and comments)

like image 102
Max Avatar answered Oct 06 '22 01:10

Max