简体   繁体   中英

How to select elements that contain   and add a class

i need to add one class to more than one element and I wanted to do it through jQuery but I am noob and I dont know how to select those elements with content of nsbp; . Here is the case:

  <ul>
       <li><a href="#" target="_blank"><b>Example</b> <br><span>Example Description</span></a></li>
       <li class="spacer">&nbsp;</li>
       <li><a href="#" target="_blank"><b>Example</b><br><span>&nbsp;</span></a></li>
       <li class="spacer">&nbsp;</li>
       <li><a href="#" target="_blank"><b>Example</b><br><span>&nbsp;</span></a></li>
       <li class="line2">&nbsp;</li>
  </ul>

Please help!

May be like this:

$("span").filter(function(){
    return $(this).html().match(/&nbsp;/) !== null;
}).addClass("some-class");

Or may be like this:

// http://en.wikipedia.org/wiki/Non-breaking_space
// In Unicode, [the non-breaking space] is encoded
// as U+00A0 (HTML: &#160; &nbsp;)
$("span:contains('\u00a0')").addClass("some-class");

If you want all the nodes that have those specific classes:

// Select all the nodes that have either the class "spacer" or the class "line2"
var elements = $('.spacer, .line2');
// Add another class
elements.addClass('newClass');

If you want all the nodes whose content is &nbsp; , then you should use the contains selector or a filter , as other answers say, but if you don't need that (or you can change the HTML so all the nodes with &nbsp; have an specific class) then selecting by class is more performant and simpler.

像这样:

$("elementYouWantAddClass").hasClass("yourClassCss"))
$(window).ready(function(){
    $('li').each(function(){
        if($(this).html()=="&nbsp;") {
            $(this).addClass('css_class_name');
        }   
    });
});

try this

$("ul li").not(':has(a)').addClass('classname');

Please ignore the above one and try the following snippet.

$('span').filter(function () {
    return $(this).html().indexOf('&nbsp;') > -1;
}).addClass('yourClass');

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM