javascript - Hide all elements with particular number in id - Stack Overflow

need help, I try to cut plexity and make simple example:<div id="tree_div"><ul>&l

need help, I try to cut plexity and make simple example:

<div id="tree_div">
   <ul>
      <li id="tree_li_401">401</li>
      <li id="tree_li_101">101</li>
      <li id="tree_li_301">301</li>
      <li id="tree_li_201">201</li>
      <li id="tree_li_102">102</li>
      <li id="tree_li_402">402</li>
   </ul>
</div>

I need to hide all li elements base on first number after tree_li_

For example: I need to hide all elements which have number 4 after tree_li_:

<li id="tree_li_402">
<li id="tree_li_401">

need help, I try to cut plexity and make simple example:

<div id="tree_div">
   <ul>
      <li id="tree_li_401">401</li>
      <li id="tree_li_101">101</li>
      <li id="tree_li_301">301</li>
      <li id="tree_li_201">201</li>
      <li id="tree_li_102">102</li>
      <li id="tree_li_402">402</li>
   </ul>
</div>

I need to hide all li elements base on first number after tree_li_

For example: I need to hide all elements which have number 4 after tree_li_:

<li id="tree_li_402">
<li id="tree_li_401">
Share Improve this question asked Nov 16, 2012 at 2:29 xsorxsor 1,07411 silver badges11 bronze badges 1
  • api.jquery./attribute-starts-with-selector – Derek 朕會功夫 Commented Nov 16, 2012 at 2:51
Add a ment  | 

2 Answers 2

Reset to default 11

You can use attribute selectors to target those elements:

$('li[id^="tree_li_4"]').hide();

Here's a list of all the attribute selectors that jQuery supports.

As stated, you can use attribute selectors, if you would like a solution for all of them, use the .each() method, and you could use a variable for the number.

example:

$("li[id='tree_li_'"+ magicNumber +"]").each(function (idx, li) {
  $(li).hide();
});

or as a one liner

$("li[id='tree_li_'"+ magicNumber +"]").hide();

and if you wanted to get really crazy, you could use the .substring() method. .substring returns true, if the string has the specified substring. i.e. "brian".substring("ria") will return with the index of the string (a positive number) and if it does not find the string, it returns as -1.

$("li").each(function(idx, li) {
  if ($(li).attr("id").substring("4")) {
    $(li).hide();
  }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744320353a4568383.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信