How to find out if a tag has a specific class AND id
Have a body tag on a page that has both an id and a class:
<body class="class" id="id">
I'm trying to use jQuery to chance some content further down the page, based on what the class AND t开发者_如何学运维he id are. I've had no success, for what it's worth, here's what I tried to do:
if($('body').is('#id1')){
if($(this).hasClass('class1')){
$('ul.nav li.first').html('<h2>Special Title</h2>');
}else if($(this).hasClass('class2')){
$('ul.nav li.first').html('<h2>Other Title</h2>');
}
}else if($('body').is('#id2')){
if($(this).hasClass('class1')){
$('ul.nav li.first').html('<h2>Special Header</h2>');
}else if($(this).hasClass('class2')){
$('ul.nav li.first').html('<h2>Other Title</h2>');
}
}
Anyone have a quick way of doing this? I'm terrible at "if" looping using jQuery, always have been.
Cheers,
T
For the record there is no need to use jQuery here.
var isId = (document.body.id === someId);
var isClass = (document.body.className.indexOf(someClass) !== -1);
if (isId && isClass) {
// do something
}
[Edit]
The class check is horrible. Try
var regexp = new RegExp("(^|//s)" + someClass + "($|//s)", "m");
var isClass = (document.body.className.search(regexp) !== -1);
Never mind. For anyone wondering, I never defined what $(this)
is. Replaced it with $('body')
and it works now.
Sorry all. Move along, nothing to see here!
精彩评论