简体   繁体   中英

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 " " as a jQuery object. ”作为一个 jQuery 对象。

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.

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>

如果你只想替换<b><\\b>标签的内容,你可以这样做:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM