开发者

Jquery Hide Class when no class is present

I have some text below called (16 Courses). I need to hi开发者_C百科de only this text, but I can't seem to hide it no matter what I try using jquery. Is there any help someone could provide so I can hide on this text?

<div id="programAttributes">
    <div class="left" id="credits">
       <h3>Credits</h3>
       <h3 class="cost">48</h3>
       (16 Courses)
    </div>
    <div class="gutter12 left">&nbsp;</div>
    <div class="left" id="costPer">
       <h3>Cost Per Credit</h3>     
       <h3 class="cost">$300</h3>                            
    </div>
</div>

I thought if I could write something like this that would do the trick, but I am so far unsuccessful.

$("#credits:not([class!=h3])").hide();


Usage

// hides in the whole document
hideText("(16 Courses)");

// only hide inside a specific element
hideText("(16 Courses)", $('#programAttributes'));

// make it visible again
showText("(16 Courses)"); 

[See it in action]

CSS

.hiddenText { display:none; }

Javascript

// escape by Colin Snover
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function hideText(term, base) {
  base = base || document.body;
  var re = new RegExp("(" + RegExp.escape(term) + ")", "gi");
  var replacement = "<span class='hiddenText'>" + term + "</span>";
  $("*", base).contents().each( function(i, el) {
    if (el.nodeType === 3) {
      var data = el.data || el.textContent || el.innerText;
      if (data = data.replace(re, replacement)) {
        var wrapper = $("<span>").html(data);
        $(el).before(wrapper.contents()).remove();
      }
    }
  });
}

function showText(term, base) {
  var text = document.createTextNode(term);
  $('span.hiddenText', base).each(function () {
    this.parentNode.replaceChild(text.cloneNode(false), this);
  });
}


You can check for and remove textnodes like this:

​$("#credits").contents().filter(function() {
  if(this.nodeType == 3) 
    this.parentNode.removeChild(this);
});​​​​​​

You can test it here, this gets all the nodes (including text nodes) with .contents(), then we loop through, if it's a text node (.nodeType == 3) then we remove it.


Could you wrap it in a separate span, and then do:

$('#credits span').hide();

?


Try wrapping the text in a span as follows:

<div class="left" id="credits">
   <h3>Credits</h3>
   <h3 class="cost">48</h3>
   <span id="toHide">(16 Courses)</span>
</div>

then you can use jquery:

$("#credits > span)").hide();

the hide() function has to be applied to a DOM element.


I would use a label tag around the text so I can handle it with jquery.


It's textnode. Loop thru all parents nodes and if it's type is textnode, hide it. See also this:

How do I select text nodes with jQuery?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜