开发者

get the next element with jquery/js

I've got some elements like

<div id="myDiv">
    <p><input type="checkbox" />text</p>
    <p>special text</p>
    <p><input type="checkbox" />text</p>
    <p><input type="checkbox" />text</p>
</div>

My aim is to check the input-boxes below the 'special text'. Therefore I created a variable findText to find 'special text'

var findText = $("#myDiv:contains('special text')");

I'm checking whether 'special text' exists and if so, I want the next input elements to be checked. .nextAll() unfortunately just gets the fo开发者_运维百科llowing siblings. But how can I call the next elements?

 var findText = $("#myDiv:contains('special text')");

    if(findText.length > 0) {
      findText.nextAll("input").attr("checked",true)
    }

Thank you for your time and help.


nextAll with a find should do it:

findText.nextAll("p").find("input").attr("checked",true);

That finds the following paragraphs, and their descendant inputs. (Or use children rather than find if the inputs are guaranteed to be immediate children of the paragraphs.)

...but I think your selector for findText is incorrect, try:

var findText = $("#myDiv p:contains('special text')");
//                      ^^^---- change here

Putting that all together:

var findText = $("#myDiv p:contains('special text')");

if(findText.length > 0) {
  findText.nextAll("p").find("input").attr("checked",true)
}

Live copy

Separately, you might consider limiting the search to just checkboxes with jQuery's custom :checkbox selector:

var findText = $("#myDiv p:contains('special text')");

if(findText.length > 0) {
  findText.nextAll("p").find(":checkbox").attr("checked",true)
  //                         ^^^^^^^^^^^-- Change here
}

Live copy


You could do it like this:

$("#myDiv p:contains('special text')").next().children('input').prop('checked',true);

Example: http://jsfiddle.net/HVSyE/3/

Edit: if you want all the checkboxes after the text to be checked, then:

$("#myDiv p:contains('special text')").nextAll('p').children('input').prop('checked',true);

Example: http://jsfiddle.net/HVSyE/4/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜