james bond
james bond

Reputation: 117

change text false and true javascripts

text replace "false" to "true"

ori from html (dont change) :

<td  align="center">false</td>

to

<td  align="center">true</td>

my js code error :

document.body.innerHTML = document.body.innerHTML.replace(/<td  align=\"center\">false<\/td>/g,"<td  align=\"center\">true<\/td>");

http://jsfiddle.net/PKM6U/

Upvotes: 0

Views: 591

Answers (3)

FabianCook
FabianCook

Reputation: 20567

Since you are new to this I would recommend you use a framework/library to make thing easier for you

jQuery have a nice selector that will help you with this

http://jquery.com/ http://jquery.com/download/ http://api.jquery.com/contains-selector/

This code will do what you want

function swapTrueFalse(){
    if($("td[align=center]:contains('true')"){
        $("td[align=center]:contains('true')").text('false')
    }else if($("td[align=center]:contains('false')"){
        $("td[align=center]:contains('false')").text('true')
    }
}

I would suggest you add a class to the element however as this will make it more efficient:

<td  align="center" class='true-false'>true</td>

Change the code to match:

function swapTrueFalse(){
    var t = $(".true-false").text()
    if(t === "true"){
        $(".true-false").text("false");
    }else{
        $(".true-false").text("true");
    }
}

Using regex to parse HTML in the way you are is extremely inefficient so I do advise against it.

Upvotes: 1

Eric Cuiffo
Eric Cuiffo

Reputation: 11

Works just fine if you replace your all "td" with "span". Having td nodes by themselves doesn't really make sense and it appears as though they disappear completely after the fiddle is ran.

Upvotes: 0

sam
sam

Reputation: 2486

<td  align="center" id="changeme">false</td>

in js

document.getElementById("changeme").text="true"

Upvotes: 0

Related Questions