Shane
Shane

Reputation: 23

Show div if another div has a certain string of text

I know this is probably easy for most of you, but being a beginner I am having a tough time.

I want to show div1 if div2 has the word foobar in it.

Upvotes: 2

Views: 1656

Answers (2)

Raynos
Raynos

Reputation: 169401

// get div 2
var div = document.getElementById("div2");
// get string content
var text = div.innerHTML;
// test if foobar is in text
if (text.indexOf("foobar") >= 0) {
    // if so set display to block.
    document.getElementById("div1").style.display = "block";
}

Oh and if you like jQuery then :

if ($("#div2").text().indexOf("foobar") >= 0) {
    $("#div1").show();
}

Although using jQuery just for this is overkill. It's a nice syntactic sugar if it's on the page anyway.

Upvotes: 5

Phrogz
Phrogz

Reputation: 303253

if (/\bfoobar\b/.test(document.getElementById('div2').innerHTML){
  document.getElementById('div1').style.display = 'block';
}

This uses a regular expression /\bfoobar\b/ to test for exactly the string "foobar" with word boundaries at either end. "foobars" will not match, but "I said 'foobar'" will.

The RegExp.prototype.test() method takes a string and returns true if the regular expression can match somewhere in it, false otherwise.

We pass in innerHTML of the div, which is like the source code inside it.

I'm assuming that you have already hidden div by setting its display style to none, either via JS or via a stylesheet, e.g.

#div1 { display:none }

Upvotes: 3

Related Questions