Ionică Bizău
Ionică Bizău

Reputation: 113345

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 :

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>!

Upvotes: 7

Views: 117

Answers (1)

Max
Max

Reputation: 1844

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)

Upvotes: 5

Related Questions