Ricky
Ricky

Reputation: 181

Using jQuery, how do I get the first parent element found with a selection of text?

I have the following element assigned to a variable, along with a set of selection indexes for this variable.

var html_element = $("<p>Some text goes <b>here</b> then continues here</p>").appendTo("body");
var start = 15;
var end = 17;

This SHOULD represent the letters "her" in the word "here". Is there any way for me to use these indexes and the html_element to get the first HTML element (parent) of the selection...? So in this case I want to grab "here" as a jQuery object.

So that if I want I can change the text "here" to anything such as "new here".

In plain terms I want to grab the first element before the start_index.

Upvotes: 1

Views: 66

Answers (2)

guest271314
guest271314

Reputation: 1

Try using :contains() to select element containing characters within html_element at indexes 15 through 17; .text(), String.prototype.slice()

var html_element = $("<p>Some text goes <b>here</b> then continues here</p>")
                   .appendTo("body");

var start = 15;
var end = 17;
// element containing charaters at parent element text indexes 15 through 17
var selected = $(":contains(" + html_element.text().slice(15, 17) + ")"
               , html_element); // set `context` to `html_element`
// set new text at `selected`
selected.text(function(_, text) {
  return "new " + text
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

alternatively, .contents() , for loops to count characters of text nodes with p element

var html_element = $("<p>Some text goes <b>here</b> then continues here</p>")
  .appendTo("body");

var start = 15;
var end = 17;

var text = 0;
var elem = null;
var contents = html_element.contents();

for (var index = 0; index < contents.length; index++) {
  var el = contents[index];
  if (elem === null && (el.nodeType === 3 || el.firstChild.nodeType === 3)) {
    var txt = el.textContent || el.nodeValue;
    for (var i = 0; i < txt.length; i++) {
      text += 1;
      if (text >= start + 1 && text <= end) {
        elem = $(el)
        break
      }
    };
  } else {
    break;
  }
};

console.log(elem, text, text >= start && text <= end);

elem.text(function(_, txt) {
  return "new " + txt
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Upvotes: 1

s4san
s4san

Reputation: 319

If you just want to replace the contents of the <b><\b> tag, you can do something like this:

html_element.find('b').text('My custom Text');

Upvotes: 0

Related Questions