在jQuery Element中查找相对元素

时间:2016-09-10 17:27:39

标签: javascript jquery dom

编辑:

改述问题,

所以基本上让我说我有两个jQuery元素,不是来自dom ,并且通过从两个中的一个中获取子元素,我需要在另一个中找到它。

var firstDiv = '<div><div id="test"><b>Something here</b><b>I want this 
element from here</b></div></div>';
var secondDiv = '<div><div id="test"><b>Something here</b><b>I want this element from here</b></div></div>';

var firstElement = $($.parseHTML(firstDiv));
var secondElement = $($.parseHTML(secondDiv));

var wantedFromSecond = secondElement.find("#test").eq(0).find("b").eq(1);
//Pretend we don't know how we got the "wantedFromSecond" element

alert(secondElement.index(wantedFromSecond[0]));

同样在这里:

https://jsfiddle.net/338h3qk9/1/

我很伤心,我们不知道wantFromSecond来自哪里。所以请不要使用$(&#34; #test&#34;)之类的东西。它也不是来自实际的dom,所以一切都必须来自firstElement或secondElement。

我希望能够很好地解释它,你也可以运行JFiddle,你就会明白我的意思。

谢谢,我很感激!

2 个答案:

答案 0 :(得分:0)

将元素转换为选择器,只需在文档中找到它。

// find in the entire document
$('<b>I want this element from here</b>');

// find in specific element
$('#test').find('b:contains("I want this element from here")');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div id="test">
    <b>Something here</b>
    <b>I want this element from here</b>
  </div>
</div>

<div>
  <div id="test2">
    <b>Something else here</b>
    <b>I want this element from here</b>
  </div>
</div>

答案 1 :(得分:0)

根据您的JSFiddle,您错误地使用了.index()。您在导入的HTML中的顶级<div>元素上使用它。您需要深入查看所需的元素,然后执行索引。

var firstDiv = '<div><div id="test"><b>Something here</b><b>I want this element from here</b></div></div>';
var secondDiv = '<div><div id="test"><b>Something here</b><b>I want this element from here</b></div></div>';

var firstElement = $($.parseHTML(firstDiv));
var secondElement = $($.parseHTML(secondDiv));

var wantedFromSecond = secondElement.find("#test").find("b").eq(1);

// use a selector specific enough to only get the <b> elements, then index those
console.log(secondElement.find('#test b').index(wantedFromSecond)));

// the following won't work because you're using index on the top level element
//console.log(secondElement.index(wantedFromSecond));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>