Javascript 从HTML字符串中的某个位置获取所有父HTML标记
有没有一种简单的方法可以从HTML字符串中的某个位置获取所有“父HTML标记” 例如:Javascript 从HTML字符串中的某个位置获取所有父HTML标记,javascript,html,Javascript,Html,有没有一种简单的方法可以从HTML字符串中的某个位置获取所有“父HTML标记” 例如: '<div><div>foo</div><p>foo2</p>foo3*caret position here*' : returns '<div>' (the first div) '<div><div>foo</div><p>foo2*caret position here* : ret
'<div><div>foo</div><p>foo2</p>foo3*caret position here*' : returns '<div>' (the first div)
'<div><div>foo</div><p>foo2*caret position here* : returns '<div><p>'
'<div><div><div>foo*caret position here* : returns '<div><div><div>'
'foofoo2foo3*此处插入符号位置*':返回“”(第一个div)
'foofoo2*此处插入符号位置*:返回''
'foo*此处插入符号位置*:返回“”
您需要将字符串转换为DOM并在树中导航
函数getAllParents(htmlStr){
//查找光标文本并用我们可以找到的元素替换它
htmlStr=htmlStr.replace('*游标*','');
//制作一个div,我们可以将html注入其中
var div=document.createElement(“div”);
//将字符串转换为我们可以导航的dom
div.innerHTML=htmlStr;
//找到光标
var cur=div.getElementsByClassName(“游标”)[0],
元素=[];
//环顾所有的父母
while(cur){
元素取消移位(cur);
cur=cur.parentNode;
}
elems.shift()//删除保存html的div
elems.pop()//删除我们注入的游标元素
return elems;//返回父元素
}
log(getAllParents(“aaa*游标*aaa”);
log(getAllParents(“*cursor*aaaaaa”);
log(getAllParents(“*cursor*aaaaaa”)代码>你喜欢使用jquery之类的javascript库吗?你指的是文字字符串还是DOM节点?问题是“字符串”,但“插入符号位置”是DOM。
parent
是一个相对术语<代码>父HTML标记属于什么?特定的
?您必须更加具体。尝试并猜测您正在使用contentEditable:并使用它来获取第一个父级,而不是简单的循环。