开发者

Jquery find all except

开发者 https://www.devze.com 2023-03-29 15:56 出处:网络
I have following HTML: <div id=\"123\" class=\"test\"> <div class=\"testMessage\">Foo</div>

I have following HTML:

<div id="123" class="test">
   <div class="testMessage">Foo</div>
   <div><div class="testDate">2010</div></div>
   <div id="127" class="test">
      <div class="testMessage">Bar</div>
      <div><div class="testDate">2011</div></div>
   </div>
</div>

And I have following JS/jQuery code:

$(".test").find(".testDate").val("cool 2010");

How开发者_开发知识库 to change JS/jQuery to find "testDate" class element except in children "test" class block without using children?

P.S. I know only about class name and I don't know how many divs can be nested.


Update

Its probably the weirdest selector I've ever written:

$("div.test").not(':has(> .test)').siblings().find('.testDate').text('cool 2010');

Demo: http://jsfiddle.net/mrchief/6cbdu/3/

Explanation:

$("div.test")             // finds both the test divs
  .not(':has(> .test)')   // finds the inner test div
  .siblings()             // get all other divs except the inner test div


Try this and also div elements do not have a value property, use html() method to set the inner html or text()

$("div.test :not(.test)").find(".testDate").html("cool 2010");

If you can modify your main div id to "_123", you can straight away use the id selector like this

$("#_123 > div.testDate").html("cool 2010");


I think the not() selector might help. You can learn more about it here: http://jsperf.com/jquery-css3-not-vs-not


Anytime you try to select $('.test'), it will grab all elements with a class='test'. You need to start at the outermost body tag:

$('body').children('.test').children(':not(.test)').find('.testDate').text('cool 2010');

0

精彩评论

暂无评论...
验证码 换一张
取 消