I am looking to be able to do this function
$( "div:contains('John')" ).css( "text-decoration", "underline" );
without using jQuery, just straight up javascript, I cant find the equivalent
I know I am looking for indexOf
, but putting it all together is not working for my current mindset.
I am looking to be able to do this function
$( "div:contains('John')" ).css( "text-decoration", "underline" );
without using jQuery, just straight up javascript, I cant find the equivalent
I know I am looking for indexOf
, but putting it all together is not working for my current mindset.
4 Answers
Reset to default 13Something like this ?
var divs= document.getElementsByTagName('div');
var len = divs.length;
for (var i = 0; i < len; i++) {
if(divs[i].innerHTML.indexOf("John") != -1) {
divs[i].className += " underline"
}
}
and in css
.underline{
text-decoration: underline;
}
Probably something like thus:
var elements = document.getElementsByTagName("div");
for (var i=0;i<elements.length;i++) {
var elem = elements[i];
if (elem.innerHTML.indexOf("John") != -1) {
// do whatever you plan to do
}
}
If you only need to support modern browsers (and achieve the aims of your posted 'for-translation' code):
var allDivs = document.querySelectorAll('div');
[].forEach.call(allDivs, function(a){
if (a.textContent.indexOf('John') !== -1){
a.style.textDecoration = 'underline';
}
});
JS Fiddle demo.
If you'd prefer it to be case-insensitive, and to avoid matching 'Johnson':
var allDivs = document.querySelectorAll('div');
[].forEach.call(allDivs, function(a){
if (/\bjohn\b/i.test(a.textContent)){
a.style.textDecoration = 'underline';
}
});
JS Fiddle demo.
As other answers have demonstrated, it's better to avoid styling the element(s) directly, and instead rely in usage of CSS class-names to style the elements, that way un-styling doesn't require unsetting individual properties of the Node.style
object. To add classes, using the above approach (again for up-to-date browsers):
var allDivs = document.querySelectorAll('div');
[].forEach.call(allDivs, function(a){
if (/\bjohn\b/i.test(a.textContent)){
a.classList.add('underlined');
}
});
JS Fiddle demo.
To highlight only, and all instances of, the name 'John' (or 'john'):
var allDivs = document.querySelectorAll('div');
[].forEach.call(allDivs, function (a) {
if (/\bjohn\b/gi.test(a.textContent)) {
a.innerHTML = a.innerHTML.replace(/(\bjohn\b)/gi, '<span class="underlined">$1</span>');
}
});
JS Fiddle demo.
References:
Array.filter()
.Array.forEach()
.document.querySelectorAll()
.Element.classList
.Function.call()
.- JavaScript regular expressions.
Regexp.test()
.
var tags = document.getElementsByTagName('div');
for (i in tags) {
var tag = tags[i];
if (tag && tag.innerHTML && tag.innerHTML.indexOf('John') > -1) {
// Your tag!
console.log(tag);
}
}
getElementByID()
, right?! – mamdouh alramadan Commented Sep 27, 2013 at 20:48<li><a class="btn" href="http://url.here">Music</a></li>
– Kender Commented Sep 27, 2013 at 20:50